Jan 6, 2012

Stateless CSRF Protection

In the era of RESTful services and rich internet applications it's important to find security solutions that don't impose unnecessary state or computation on servers. I previously wrote a post on stateless session ids. Let's have a look at how we can protect against cross-site request forgeries (CSRF) without server-side state.

CSRF Basics
Forged requests are nasty attacks. They rely on the fact that your browser automatically adds cookies to HTTP requests if it has cookies associated with the target domain and path. That includes session cookies.

Let's say you're currently authenticated to twitter.com. If you visit another site on another domain that site can issue requests to twitter.com and your Twitter session cookie will be added to those requests.



How can domain B issue requests to domain A, formally doing a cross-site HTTP request? Well, there are some obvious cases – images, JavaScript, and CSS.

<img src="whatever.domain.org/path/logo.png" />

… is allowed from any site, which means a malicious site can contain tags like …

<img src=”https://secure.bank.com/checkAccounts" height=0 width=0 />

Such a tag will issue an HTTP GET to secure.bank.com/checkAccounts including the victim's session cookie for *.bank.com should he or she be logged in. The browser doesn't know if there's an image on that URL or not. It just fires the request. And by setting the image size to 0x0 the victim will see nothing.

CSRF With POST
Most sensitive stuff require an HTTP POST since a GET should be idempotent and not change any state server-side. So can a malicious page issue an HTTP POST to any domain? Yes.



The CSRF code from the image above ($ is jQuery):

<form id="target" method="POST" 
 action="https://1-liner.org/form">
  <input type="text" value="I hate OWASP!" name="oneLiner"/>
<input type="submit"
 value="POST"/>
</form>


<script>
  $(document).ready(function() {
     $('#target').submit();
  });
</script>

CSRF Against RESTful Services
But maybe you've left HTML forms behind and go with rich clients, a RESTful backend and communication via JSON? Can a malicious page issue an HTTP POST targeting such services? Yes.

You can change the encoding of HTML forms to text/plain and do some tricks to produce parseable JSON in the request body. Here's an example that I got working with a Java JAXRS backend:

<form id="target" method="POST" 

action="https://vulnerable.1-liner.org:
8444/ws/oneliners" 

style="visibility:hidden"
 enctype="text/plain">
  <input type="text"

   name='{"id": 0, "nickName": "John",
          "oneLiner": "I hate OWASP!",

          "timestamp": "20111006"}//'
   value="dummy" />
  <input type="submit" value="Go" />

</form>

Notice the enctype and that the JSON is in the input name, not the value. The above form produces a request body looking like this:

{"id": 0, "nickName": "John","oneLiner": "I hate OWASP!","timestamp": "20111006"}//=dummy

… which is accepted by for instance the Jackson parser.

CSRF Protection With Double Submit
Traditional anti-CSRF techniques use tokens issued by the server that the client has to post back. The server validates the request by comparing the incoming token with it's copy. But that small word "copy" means server-side state. Not good.

Double submit is a variation of the token scheme where the client is required to submit the token both as a request parameter and as a cookie.



A malicious page on another domain cannot read the anti-CSRF cookie before its request and thus cannot include it as a request parameter.



Two Misconceptions About Double Submit
There are two common misconceptions about the double submit CSRF protection.

First, it has been suggested that the session cookie should be used for this purpose. Since you have to use JavaScript to pick up the cookie value and add it as a request parameter the cookie cannot have the HTTPOnly attribute. And you want HTTPOnly on your session cookie to prevent session hijacking via cross-site scripting.

But you should not use the session cookie as anti-CSRF cookie. Instead add a specific anti-CSRF cookie which does not have the HTTPOnly attribute and keep your session cookie protected.

Second, people have stuck with server-generated, stateful anti-CSRF cookies. But double submit cookies can be generated client-side and don't have to be saved by the server at all.

Stateless CSRF Protection with Double Submit
The protective measure of double submit lies in the fact that a malicious site cannot read the cookie and include it as request parameter. That condition still holds if the cookie is generated by the client and never saved by the server.

So let the client generate the anti-CSRF value and only compare and check format of cookie and request parameter on the server. Ergo, stateless CSRF protection!



Hardening the Double Submit Protection
Double submit protection breaks down if the attacker somehow can read or set the anti-CSRF value. We can harden double submit against malicious reads.

First of all we make the client change the anti-CSRF value upon every request. This is typically done by centralizing backend calls to a custom AJAX proxy, possibly inherited.

Second, we zero the anti-CSRF cookie directly after each backend call. This will allow for accurate server-side detection of forged requests. A zeroed double submit cookie is a clear signal of either a client-side bug or a forged request. With zeroed anti-CRSF cookies the attacker has to issue his/her attack to exactly when the cookie is set by the client.

Drawbacks of Double Submit
You typically hear two drawbacks of the double submit protection – it's reliance on JavaScript to add the cookie value as request parameter, and the possibility to read the anti-CSRF cookie via cross-site scripting.

The issue with JavaScript is diminishing as JavaScript is becoming a requirement for more and more sites anyway.

The cross-site scripting critique is invalid. If you can script the site you already own all of it and can setup your own AJAX proxy, read any tokens in the DOM etc.

Dec 17, 2011

The Anatomy of a Twitter Storm

Hi! I'm @johnwilander and yesterday I unwillingly created a Twitter storm.

#GodIsNotGreat and Twitter Trends
It was Friday afternoon in Stockholm, Sweden and I came across a tweet with the interesting tag #GodIsNotGreat. Earlier that day I had read about famous atheist and writer Christopher Hitchens passing away but there was something else going on around this tag. In the tag stream I read about christians threatening tweeters using the tag and several claims that Twitter had pulled the tag from the trends list.

I couldn't find the tag in my trends list nor in the US or European list. Still, tweets with the tag were pouring in. In the stream I found a tweet from @HillyFoz saying:

"So Twitter, it's ok for #reasonstobeatyourgirlfriend to trend but you saw fit to put a stop to #GodIsNotGreat ?"

Apparently #ReasonsToBeatYourGirlfriend had been a trend. Now that's interesting too. So I wrote The Tweet what would become a Twitter storm:


As you can see in the screenshot, numerous people eventually retweeted this.

I could see the amplification within a minute. Suddenly around 10 people had retweeted it and new retweets where being reported faster than I could open them on the activity tab.

At this point I reviewed my tweet and saw that I had claimed something I couldn't back up with a source or a reference. Such things make a about-to-be-PhD blush a little :). Soon enough I started to get complaints. I considered deleting the tweet but decided to let it live on to see what this storm would be like.

Here Come the Trending Bots
Time for the first bot to spot me. Apparently I was trending in the UK:


While the retweets, complaints and comments were pouring in I quickly became a trend in USA and Canada too:



About 30 minutes later the spam bots had caught on and I started getting all kinds of weird stuff. Some of them I couldn't tell if they we're real people or bots. For instance this (not even a reply to my tweet):


I did not respond :).

The final bot step was when the @favstar50 bot congratulated me to my first 50+ favorited tweet.

Trying to Find a Source
Some of the complaints I got where getting nasty so I thought I might be lucky enough to find a source and patch my earlier tweet. UK online paper Huffington Post gave me at least half an excuse as they wrote:

"The hash tag #GodIsNotGreat also began trending, which was followed by a storm of protests by the religious, many unaware that the hash tag was a tribute to the author's passing.


Twitter reportedly removed the topic from the trending lists following threats of violence towards the creators of the hash tag. The irony that Hitchens book, one that makes stark the link between religion and violence, had stirred the religious to then threaten violence was not lost on the twitterati."

But my antagonists quickly dismissed Huffington Post as a bad source and also pointed out that they said "reportedly" which I failed to do in my 140 chars. So much for the patchwork.

The Day After
When I got up Saturday I checked my email. Well ...


I had got quite a few new followers. Woot! But I guess most of them will unfollow when I go back to tweetin' about JavaScript and application security. Easy come, easy go, huh? Note the browser tab for Twitter with 19 new notifications that dropped in while I was taking the screenshot.

I checked my Klout score:


It looks like the revenue diagrams Uncle Scrooge has on his wall :).

Later I found out that Gizmodo had written an article about it – Shutup, Twitter Isn't Censoring Your Dumb Trends. There, in the middle of their bashing was my tweet! Luckily, Gizmodo didn't dig out the source but rather took poor Jessica K's commenting retweet as an example. Phew.

Lessons Learned
My lessons learned:
  • I should probably check the sources of every tweet, not just my tech tweets.
  • Rumors spread extremely fast on Twitter. As long as the message is interesting, people retweet.
  • Twitter trends are not based on volume, they're based on derivatives, or speed if you will. If the increase of the #GodIsNotGreat tag would have been steady it would have still been a trend. But it wasn't.

Apr 9, 2011

REST and Stateless Session IDs

Nowadays there's a general reluctance to introduce (more) server-side session state because of scalability. And there's specific reluctance to session state in RESTful web services, due to design principles.

In the stateless requirement of REST we read:

"The client–server communication is constrained by no client context being stored on the server between requests. Each request from any client contains all of the information necessary to service the request, and any session state is held in the client. The server can be stateful; this constraint merely requires that server-side state be addressable by URL as a resource." [Wikipedia]

This is a tough requirement, especially if we want features such as authentication and sessions.

So, can we have session ids without server-side session state? Yes.

The Relation Between Sessions and Authentication
There's often a tight relationship between authenticating users and holding their sessions. Anonymous sessions are not very sensitive whereas authenticated sessions have to be protected against hijacking, fixation, forging, and replay. Actually, a valid session token authenticates the session, so you're basically authenticating yourself every request. Which leads us to the first stateless session solution ...

No Sessions => Authenticate Every Request
If session ids are in fact authentication tokens we might as well use the mental model of no sessions, instead authenticate each request. The old HTTP Basic Authentication does this by storing your username and password for subsequent requests. But there are more advanced versions such as authentication in Amazon's S3 REST API.

They use a custom HTTP scheme based on a keyed-HMAC (Hash Message Authentication Code). To authenticate a request, you first concatenate selected elements of the request to form a string. You then use a shared "AWS Secret Access Key" to calculate the HMAC of that string, i.e. you sign the request. Finally, you add this signature as a parameter of the request.

GET /photos/puppy.jpg HTTP/1.1
Host: johnsmith.s3.amazonaws.com
Date: Mon, 26 Mar 2007 19:37:58 +0000


Authorization: AWS 0PN5J17HBGZHT7JJ3X82:frJIUN8DYpKDtOLCwo//yllqDzg=


Looking deeper into how this scheme works you find the following spec:


Authorization = "AWS" + " " + AWSAccessKeyId + ":" + Signature;


Signature = Base64( HMAC-SHA1( UTF-8-Encoding-Of( YourSecretAccessKeyID, StringToSign ) ) );


StringToSign = HTTP-Verb + "\n" +
________Content-MD5 + "\n" +
________Content-Type + "\n" +
________Date + "\n" +
________CanonicalizedAmzHeaders +
________CanonicalizedResource;


Canonicalization of course requires some processing such as converting headers to lower-case and sorting them lexicographically. The date works as a timestamp and narrows the replay window.

The server then does the same signing with the shared secret associated with the AWSAccessKeyId. So we're switching from server-side session state to more cycles and latency on both client and server.

Worth noting:
  • Signed requests are much stronger than mere session ids. Cross-site request forgeries will be mitigated with this scheme.
  • By authenticating all requests with a shared secret we don't have any time-bound sessions or timeouts. Just fire whenever you want.
  • The persistent shared secret is much more sensitive than a temporary session id. A cross-site scripting attack will steal the shared secret which is much worse than session hijacking. This means the scheme is less suitable for browsing sessions and more suitable for machine-to-machine communication.

Stateless, Hashed Session ID and Salt
The server can generate session id cookies by hashing usernames and a random global salt:

sessionIdCookie_v1 = username ":" SHA256(username + global salt)

The salt is used for all sessions but only valid for a certain timeframe, say 15 minutes. A new salt is produced every 5 minutes and incoming session ids produced with the previous but still valid salt will be exchanged for a new session id with the fresh salt. That means a session timeout of 15-5=10 minutes.

If we truly want to go stateless we cannot kill such a session since that would require a server-side table of revoked session ids. So in the stateless case an attacker will have a 15 minute replay window in which he/she will refresh the session and have endless access.

Stateless, Encrypted Session ID
By just storing a server-side symmetric crypto key we can effectively decrypt incoming session IDs and trust their contents. Imagine a cookie based on:

sessionIdCookie_v2 = AES_GCM(128 bit key, auth tag, username + timestamp)

This means we don't have to store each session ID. Instead we pay the price of decrypting incoming cookies and checking that the timestamp is within a timeframe, say 15 minutes. For all incoming session IDs older than 5 minutes we regenerate a new cookie to effectively run a 15-5=10 minute session timeout window.

Again, if we want to go stateless we cannot kill such a session since that would require a server-side table of revoked session ids. So an attacker will have a 15 minute replay window in which he/she will refresh the session and have endless access.

Conclusion
There are three competing parameters to prioritize between:
  • Server CPU cycles per request
  • Server-side session state
  • The replay window
The tradeoff between CPU cycles and memory footprint will change with new technologies such as non-blocking IO in node.js. So yesterday's best practice might not be valid today.

The difference between regular session hijacking and hijacking of stateless session ids is that successful theft of a stateless session id authenticates the attacker even if the victim has logged out. Remember, the server doesn't store the session state. And even if the server would store the boolean isLoggedIn for each user, an old session id will still be valid if the user logs in again, as long as it hasn't timed out.

So ask yourselves what your tradeoff between CPU cycles and server-side state is. Then consider the replay+refresh leverage of a successful cross-site scripting attack.

Apr 8, 2011

Friday JavaScript & Web Dev Links

I'm summing up some reading tips for JavaScript and web development. Just thought you'd like 'em.

JavaScript

Command-Line JavaScript on Rhino
So you want to write command-line JavaScript on Rhino? Here's how you do it on Mac OS:
  1. Download Rhino 1.7R2: http://www.mozilla.org/rhino/download.html
  2. Unzip Rhino in for instance Applications/Utilities/Java
  3. Download JLine: http://jline.sourceforge.net/
  4. Unzip JLine in for instance Applications/Utilities/Java
  5. Move jline-0.9.94.jar to /Library/Java/Extensions
  6. In a shell: cd /Applications/Utilities/Java/rhino_1_7R2
  7. In the very same shell: java org.mozilla.javascript.tools.shell.Main
Code away!

Building Large-Scale jQuery Applications
A good read on RIA architecture and links to lib and framework choices, not only for jQuery junkies:

JavaScript Primitive Types Becoming Objects
About JavaScript's primitive types and how they become objects when their properties are used:

Scoping and Hoisting in JavaScript
If you haven't looked into scoping and variable assignments in JavaScript, read this and improve your programs:

'String'.replace() Only Replaces First Instance
String.prototype.replace, i.e. 'yourString'.replace(), only replaces the first instance of the regexp. So beware. Twitter made the mistake and got vulnerable because of it. Read about it and a suggested patch:

Non-Blocking JavaScript Loading (and more) With head.js
With Head JS your scripts load like images - completely separated from page rendering, and in parallel!

Web Development

RESTful Design, Patterns and Anti-Patterns
A nice webcast on REST design. For instance brings up the idea of session ids with constant state on the server. But as always, I wonder when the CSRF storm is going to hit all these REST services out there?

Chrome Web Dev Extensions
Google Chrome is becoming many web developers' favorite browser. The bundled developer tools are good. But check out the extensions too, for instance the CSS reloader:

iframe Loading Techniques and How They Affect Performance
Want your iframes to stop blocking and allow onLoad to fire earlier? Check these techniques out:
http://www.aaronpeters.nl/blog/iframe-loading-techniques-performance


Did I miss a good resource or read? Just fire away below.

Mar 24, 2011

The new security features in Firefox 4

The new security features in Firefox 4.

  • Content Security Policy (CSP). This is completely new opt-in security innovation and it's among the first to address the Internet plague called cross-site scripting (XSS). Currently Firefox 4 is the only browser supporting CSP but Webkit browsers (Chrome and Safari) are developing their own flavor. The feature lets the developer specify a whitelist of source domains for JavaScript, images, media, and styling. The servers passes on the whitelist policy in a response header and the browser then enforces the policy for all subsequent resource loads when rendering the page. CSP also demands that all JavaScript code be loaded from files and not be inline. Since XSS attack code typically is either from a domain not on the whitelist or inline, the browser will not execute it if CSP is enabled. Coming up with the correct whitelist and moving all your JavaScript to files will be a burden on developers so adoption will take time. Twitter has already deployed a CSP on mobile.twitter.com and will enable it for twitter.com after a trial period (http://engineering.twitter.com/2011/03/improving-browser-security-with-csp.html).
  • HTTP Strict Transport Security (HSTS). This is also a policy mechanism. It allows developers to tell browsers that this domain should only be accessed over SSL and the certificate may not cause any browser warnings. The policy is again sent via a response header so you would think it could be included in CSP. But there is a crucial difference. HSTS also specifies a time for how long in the future the browser should enforce it. After all the policy directive is about future requests. So the browser caches the HSTS policy for a whole domain and possibly for its subdomains which is fundamentally different from CSP which applies its policy to each page individually and allows a new policy on every request. PayPal have been one of the main contributors to HSTS and have deployed a policy for some time. HSTS is already supported by Chome and the Firefox plugin NoScript.
  • X-Frame-Options (XFO). Again, a response header security directive, originally a Microsoft innovation. It specifies whether the page should be allowed to be framed by another page or not. As such it's a partial countermeasure for clickjacking. But it really shouldn't be presented as such, rather a non-framing option for developers.
  • ES5/JavaScript Strict-Mode. Another Firefox first. JavaScript, formally named EcmaScript, is evolving and in version 5 there is an opt-in "strict mode" which gets rid of many of the nasty things in earlier versions. Attackers love the old oddities whereas developers hate them. So we can probably look forward to a fairly good adoption rate out there as soon as other browsers implement it (current statushttp://kangax.github.com/es5-compat-table).
  • Do-Not-Track (DNT). This is a privacy feature requested by the US Federal Trade Commission and jointly designed by Stanford Security Lab and Law School. It's an opt-in request header, i e sent by the browser not the server, which specifies that the enduser doesn't want to be tracked. This is of course a major issue for advertise-driven companies such as Google and Facebook who earn money on tracking endusers and serving them in-context ads. Security professionals are arguing that nobody will be able to know if they've been tracked anyway so we'll probably have to wait for large enduser adoption and a public lawsuit on some major company before DNT starts to mean something.

Mar 21, 2011

The 5 Complexity Dimensions of Software

I've used this image on countless occasions in my talks on software and on application security. I got it from an academic research presentation back in 2004 or so.

The 5 Complexity Dimensions of Software
 
Complexity in this regard means complex for humans to understand and contribute to.
  1. Scale. The larger the system, the more complex.
  2. Diversity. The more frameworks, languages, integration techniques, tools, platforms, and design patterns used, the more complex.
  3. Connectivity. The more connections, the more complex. This relates to coupling.
  4. Dynamics. The more number of states or the larger state space, the more complex.
  5. Refinement. Over time every living piece of software is refined, optimized, and polished. Corner cases are found and handled, and regression test suites grow. Refinement drives complexity.
In the context of application security there's always a relation between security and complexity. The more complex a system gets, the higher the risk of security vulnerabilities. Therefore managing application security is partly about managing the five dimensions above.

Sadly, computer science undergraduates rarely meet or learn about this kind of software complexity. That's why industry is reluctant to hire them. Solving 100 coding assignments comprising 200 lines of code each, just doesn't equal developing a system of 20,000 lines of code.

Tomorrow I will give a talk on why and how CS undergrads at Linköping University should learn about software complexity.

Mar 1, 2011

A Client-Oriented OWASP

Right now there are tons of thoughts, ideas, and discussions on where OWASP should go. I'm beginning to see an image of a Client-Oriented OWASP (thanks Dinis, for finding the word). In that image there are great initiatives as well as a few things we have to set straight.

Current New Initiatives
A few samples of the thoughts going around: Jeff Williams sent his OWASP 4.0 email, I wrote about the gap between appsec and developers, Mark Curphey wrote about OWASP reaching a tipping point, and Michael Coates wrote about a vision for OWASP.

Since then Michael started the Defenders Community and I started the Developer Outreach Initiative which will become the Builders Community shortly.

Client-Oriented Part 1 – Builders and Defenders
If you combine the Defenders and Builders initiatives, a new, more client-oriented OWASP emerges. Client-oriented in the sense that we put more effort into understanding and helping the IT industry who builds, operates and maintains web applications. On the less technical side we're doing this already with processes and guides – great!

But on the more technical side, OWASP needs to mix up the pentesting and appsec tooling with how to defend and how to build secure webapps. And that for me means Builders and Defenders projects but also gearing our conferences and chapters more towards builders and defenders.

I'm not saying we should cut down on pentesting or scanning tools. I love pentesters and ethical hackers. Heck, I read and retweet your blogs daily. I'm also very interested in static analysis tools, proven by my publications in the area in 2002 and 2005. I'm just saying we need to address a larger crowd and get more balance into our efforts.

Client-Oriented Part 2 – Dealing With Independence
"Our freedom from commercial pressures allows us to provide unbiased, practical, cost-effective information about application security." —About OWASP

Independent or unbiased has two parts in my opinion:
  1. OWASP should be independent in the statements it publishes, all the way from chapters to the board.
  2. OWASP should not avoid certain projects, results, or discussions only because some individual/corporate member or sponsoring organization will be upset.
Right now I think OWASP is doing fine on number one. I hear no bashing nor promoting of brands or vendors except for publicly thanking them for their support. Thank you supporters!

But number two is worrying me. At AppSec NYC 2008 there was a talk on comparing static analysis tools called "NIST and SAMATE Static Analysis Tool Exposition" (video). Some well-known brands were in the study. But the speaker refused to show figures for individual tools. There seemed to be a consensus in the community that we should not present anything that could be interpreted as negative for certain vendors, not even if the test setup was made totally transparent. That's a violation of point two above, in my opinion.

2.5 years have gone and we're still not using our independence to compare and test appsec tools. Why? John Steven, an OWASP leader with immense experience in static analysis has published serious obstacles to comparing static analysis tools but they are all saying "Just don't make your tool choices based on a general comparison" which is good advice. We should tell people that. But we still need to start putting appsec tools to the test.

Creating the Client-Oriented OWASP means we'll have to start doing independent, client-oriented research. And if OWASP has been implicitly silenced before I will not take it anymore. Here's a list of ideas:
  • Commit to Stefano Di Paola's brand new OWASP Myth Breakers Project.
  • Create a space for customer comments on appsec tools (free as well as commercial). Something like AppStore reviews, good and bad.
  • Start to compare blackbox and whitebox scanning tools. I suggest we go for a synthesized testbed (i.e. a controlled environment) and invite tool vendors/builders to take part. They get a workday to configure their tools and then we go. The testbed, configurations, and versions will all be published along with due reservations such as John Steven's.
  • Start to organize free pentests and design reviews of open platforms. In the best case we cooperate, in the worst case we make our information public in an ethical way to help clients make the right choices.
  • Sign the Open Letter to WebAppSec Tool and Services Vendors: Release Your Schemas and Allow Automation