I am not a .NET developer and I am trying to understand how exactly does __ViewState protect against CSRF/XSRF attacks.
I came across the following :
security Stack exchange discussion on similar topic and OWASP Guide to CSRF Protection
I am a little confused with how exactly is the CSRF protection happening here. If we look at the below code taken from the OWASP link mentioned above:
private const string AntiXsrfTokenKey = "__AntiXsrfToken";
private const string AntiXsrfUserNameKey = "__AntiXsrfUserName";
private string _antiXsrfTokenValue;
protected void Page_Init(object sender, EventArgs e)
{
// The code below helps to protect against XSRF attacks
var requestCookie = Request.Cookies[AntiXsrfTokenKey];
Guid requestCookieGuidValue;
if (requestCookie != null && Guid.TryParse(requestCookie.Value, out requestCookieGuidValue))
{
// Use the Anti-XSRF token from the cookie
_antiXsrfTokenValue = requestCookie.Value;
Page.ViewStateUserKey = _antiXsrfTokenValue;
}
else
{
// Generate a new Anti-XSRF token and save to the cookie
_antiXsrfTokenValue = Guid.NewGuid().ToString("N");
Page.ViewStateUserKey = _antiXsrfTokenValue;
var responseCookie = new HttpCookie(AntiXsrfTokenKey)
{
HttpOnly = true,
Value = _antiXsrfTokenValue
};
if (FormsAuthentication.RequireSSL && Request.IsSecureConnection)
{
responseCookie.Secure = true;
}
Response.Cookies.Set(responseCookie);
}
Page.PreLoad += master_Page_PreLoad;
}
From what I can understand, the above code checks to see if there is a cookie named, '__AntiXsrfToken', already present.
If not, then a new random value is generated, which is assigned to ViewStateUserKey and also set as the value for the cookie, '__AntiXsrfToken'.
If the cookie is already present, the value of the cookie is simply taken and is assigned to ViewStateUserKey.
Now what I do not understand is that the whole point about an antiXSRF token is that it should not be guessable and certainly not be passed in cookies, because cookies will always be sent with every request by the browser. In the above case, since the AntiXsrf token is being used in as cookies, how does it protect against it? And what really is the use of ViewStateUserKey and how does it play a role in the protection against XSRF here?