Clickjacking Defense

Stanford Web Security Research recently published a paper on clickjacking defense:

http://seclab.stanford.edu/websec/framebusting/framebust.pdf

The Stanford defense is lacking because Internet Explorer requires the full body to be loaded before the script will execute properly. That means that you need the <style> element at the end of the document HEAD (so that it will override any other stylesheets or inline styles) and the <script> at the end of the BODY. It is too easy to mess up, especially on platforms with multiple templates and includes, and on longer pages it can make the page seem "broken" since the script to display the body won't fire until the entire body is loaded.

Jason Li at Aspect Security came up with the concept for a way to get everything in one place in the document HEAD:

First apply an ID to the style element itself:

<style id="antiClickjack">body{display:none !important;}</style>

And then delete that style by its ID immediately after in the script:

<script type="text/javascript">
    if (self === top) {
        var antiClickjack = document.getElementById("antiClickjack");
        antiClickjack.parentNode.removeChild(antiClickjack);
    } else {
        top.location = self.location;
    }
</script>

This way, everything can be in the document HEAD and you only need one method/taglib in your API.

This method has now been tested in IE6/7/8, FireFox 3.x, and the latest versions of Chrome, Safari and Opera. I would love to hear from anyone who can test/verify this in any other browsers.

Update! 2010-10-29: Chris Schmidt reports that this defense also works perfectly in IE6 (appended above).

Update! 2011-01-31: Brendon Crawford suggested to use === to ensure type equality (appended above).