Preventing Clickjacking Attacks in ColdFusion

What is Clickjacking Attack?
As per OWASP,
Clickjacking, also known as a “UI redress attack”, is when an attacker uses multiple transparent or opaque layers to trick a user into clicking on a button or link on another page when they were intending to click on the the top level page. Thus, the attacker is “hijacking” clicks meant for their page and routing them to another page, most likely owned by another application, domain, or both.

Lets see an example:

  1. A visitor is lured to evil page. No matter how, may be by clicking on an email.
  2. This page will contain a link called “Get FREE IPOD” with z-index set to -1;
  3. This page also contains a transparent iframe from the victim domain, say facebook.com and positions the facebook like button right over the link.So now the facebook like button is not visible , but the “Get FREE IPOD” link is visible. Now if the user will clickon this link unknowingly he is clicking of the facebook like button.

Here is an example:

<html>
    <head>
        <script>
          window.fbAsyncInit = function() {
            FB.init({
              appId      : '754831697896892',
              xfbml      : true,
              version    : 'v2.1'
            });
          };
    
          (function(d, s, id){
             var js, fjs = d.getElementsByTagName(s)[0];
             if (d.getElementById(id)) {return;}
             js = d.createElement(s); js.id = id;
             js.src = "//connect.facebook.net/en_US/sdk.js";
             fjs.parentNode.insertBefore(js, fjs);
           }(document, 'script', 'facebook-jssdk'));
        </script>
        <style>
            iframe { /* iframe from facebook.com */
              width:140px;
              height:100px;
              margin-top: 100px;
              margin-left: 50px;
              position:absolute;
              top:0; left:0;
              filter:alpha(opacity=50); 
              opacity:0.5;   //Here we have set the opacity to 0.5 so its partly visible, we can make it 0 to hide the iframe
            }
            .a{
                margin-top: 95px;
            }
        </style>
    </head>
    <body>
        <div class="a">
            <a  href="http://www.google.com" target="_blank" style="position:relative;left:20px;z-index:-1">Get Free IPOD!</a>
        </div>
        //www.facebook.com/plugins/like.php?href=https%3A%2F%2Fwww.facebook.com%2FTimesnow&width&layout=button&action=like&show_faces=false&share=false&height=35&appId=754831697896892
    </body>
</html>

JS fiddle: http://jsfiddle.net/5e5kvxk4/4/

Facebook Like button,twitter Follow button already attacked this way multiple times before.http://nakedsecurity.sophos.com/2011/03/30/facebook-adds-speed-bump-to-slow-down-likejackers/.

Q. Does my site is vulnerable clickjacking attacks?

If  there is an action on your site that can be done with a single click – it may be clickjacked.

Defense:

The most common defense, called frame busting, prevents a site from functioning when loaded inside a frame. But there are some cases where the page is intended to be open inside an iframe for example facebook Like and twitter Follow buttons. So they suffer from clickjacking attacks. So to prevent this kind of attacks facebook and twitter opens a popup asking for confirmation when user clicks on the iframe.

Frame Busting:

This is the technique which prevents a site from loading inside an iframe. This technique is very easy to implement also. We just need to add ‘X-Frame-Options’ to our response header. This option is used to indicate the browser weather or not to allow a page render inside <iframe>,<frame>,<object>.

There are three possible values for X-Frame-Options:
DENY
The page cannot be displayed in a frame, regardless of the site attempting to do so.
SAMEORIGIN
The page can only be displayed in a frame on the same origin as the page itself.
ALLOW-FROM uri
The page can only be displayed in a frame on the specified origin.

We can configure at web server level to send X-Frame-Options header for all pages of our site.

IIS

<system.webServer>
  ...
  <httpProtocol>
    <customHeaders>
      <add name="X-Frame-Options" value="SAMEORIGIN" />
    </customHeaders>
  </httpProtocol>
  ...
</system.webServer>

Apache

Header always append X-Frame-Options SAMEORIGIN

Configuring Coldfusion server for preventing Clickjacking attacks:

  1. Open the file Web.xml located inside server-root/WEB-INF.
  2. Now we can add filter mappings for our application with one of the two filters already specified.
    CFClickJackFilterSameOrigin or CFClickJackFilterDeny.
  3. Now let’s say we have an application testsite, which we want to protect against clickjacking by denying a frame for the application. To do so, add the following in the web.xml file.
    <filter-mapping> 
        <filter-name>CFClickJackFilterDeny</filter-name> 
        <url-pattern>/testClick/*</url-pattern>
    </filter-mapping>

Inheritance In JavaScript

In my previous blog I had discussed about creating Objects in JavaScript. As we know JavaScript is a class-less language,so in this blog I will discuss about how Javascript supports inheritance at Object level. Javascript supports prototypical inheritance instead of regular classical inheritance.

Now lets discuss about two important concepts of prototypical inheritance in JavaScript, i.e __proto__ and prototype.

prototype
prototype is a property belonging only to functions. It is used to build __proto__ when the function happens to be used as a constructor with the new keyword.

__proto__
It is a property that all objects have and  pointing to its prototype. This is the property which is used by the JavaScript engine for inheritance. __proto__ is the actual object that is used in the lookup chain to resolve methods.According to ECMA specifications it is supposed to be an internal property, however most vendors allow it to be accessed and modified.

Ex:

function Point(x, y) {
   this.x = x;
   this.y = y;
}
var myPoint = new Point();
console.log(myPoint.__proto__ === Point.prototype); //true
console.log(Point.__proto__ === Function.prototype);  //true

Here Point is a constructor function, it builds an object (data structure) procedurally.
As myPoint is an object constructed by Point(), so Point.prototype gets saved to myPoint.__proto__ at the time of object creation.Point is a constructor function,so it has a prototype property.In javascript functions are also treated as objects,
So Function.prototype gets saved to Point.__proto__   at the time of creation of the function.

CaptureNow lets discuss about how we can inherit objects in JavaScript using prototypical inheritance.

Inheriting a Object created using Object literal syntax:

Object.create():

Douglas Crockford created the Object.create() method, which is used in a fundamental way to implement inheritance in Javascript.The crux of the matter with this Object.create method is that we pass into it an object that we want to inherit from, and it returns a new object that inherits from the object we passed into it.

Ex:

var Point = {x:4 , y:5};
var ColorPoint = Object.create(Point);
ColorPoint.color = "Red";
console.log(ColorPoint.__proto__ === Point);  //true  
console.log(Point.__proto__ === Object.prototype); //true

This creates a new object named ColorPoint by inheriting the properties of Point object and added a new property called ‘color’. Object.create() method simply sets the __proto__ property of ColorPoint object to Point object. This is called as prototypical inheritance.

Inheriting a Object created using constructor function:

In this case to implement inheritance we will write our own custom function named inheritPrototype(childObj,parentObj) which will accept the child and parent object as function parameter and will set the childObject prototype to parentObject’s prototype, so that child object can inherit everything from parent object. Let’s see how we can do this.

Ex:

// constructor of Point object
function Point(x,y){
    this.x = x;
    this.y = y;
}
Point.prototype = {
    dist: function(){
        return Math.sqrt((this.x*this.x)+(this.y*this.y));
    },
    toString: function(){
         return "("+this.x+", "+this.y+")";
    }
}

Here we have created Point Object’s constructor and added to methods to its prototype. These two methods will be shared by all the instances of Point Object.

// constructor of ColorPoint Object
function ColorPoint(x, y, color) {
    Point(this, x, y);
    this.color = color;
}
inheritPrototype(ColorPoint,Point);

Here inside ColorPoint constructor we are calling to Point object constructor to set the properties for x any y and then added a new property named Color. Finally, we are calling inheritPrototype method to inherit the methods from Point object to ColorPoint.

function inheritPrototype(childObject, parentObject){

    // so the copyOfParent object now has everything the parentObject has 
    var copyOfParent = Object.create(parentObject.prototype);

    // we are manually setting the constructor of copyOfParent object to childObject,as in the next step we will override the prototype
    of the childObject with copyOfParent.
    copyOfParent.constructor = childObject;

    // we set the childObject prototype to copyOfParent, so that the childObject can in turn inherit everything from copyOfParent 
    (from parentObject).
    childObject.prototype = copyOfParent;
}

inheritPrototype() simply set the the prototype of ColorPoint to Point object’s prototype, so it inherits its methods.

var p = new Point(3,4);
var p1 = new ColorPoint(5,6,"red");
console.log(p.toString());
console.log(p1.toString());

I hope this helped you to understood at least the general concepts of Inheritance in JavaScript.Comment if you have any doubts.

Autoversioning JS and CSS files using ColdFusion

Before going through the technique of auto-Versioning JS/CSS files, lets first understand,

What is versioning and Why versioning is required?

When we update javaScript or css files that are already cached in user’s browsers, most likely many users won’t get that for some time because of the caching at the browser or intermediate proxy(s). So we need some way to force the browser/proxy to download the latest files. So to do this either we need to change file names or URL of the files each time we change the file. As changing the file names each time after modification is not possible, so we can add a version number to the JS/CSS files to get the latest copy from the server. This technique is called as versioning.

Ex: <script type="text/javascript" src='js/global.js?v=1.2'></script>

Problem With this Approach:

The above mentioned technique works fine when we have less number of js/css files in our project. Soon it becomes very cumbersome to maintain when the project gradually becomes larger and involves a lot of js/css files for different modules.
As each time we modify some js/css files we need to update the version number in all the files where these files are included. To overcome from this problem normally 2 approaches are used by developers are:

  • 1st Approach:
    Declare a global constant called VERSION, and use this CONSTANT with all the js/css files.So with each new release we can change the verisonnumber. Ex:

    <cfset version = 1.1>
    <cfoutput>
         <script type="text/javascript" src="a.js?v=#version#"></script>
    </cfoutput>

    The problem with this approach is,
    Let’s say we are having 20-30 js/css files are used in our project, Suppose for the current release we have modified only 2/3 js files. Now we need to change the global version number.So by changing the global version number it will force all the js/css files to be reloaded again but will not use the cache. This creates very bad user experience for sites having huge traffic.

  • 2nd Approach:
    One better solution is to append the file last modified date time as the version number so that each time we modify a file, the user will get the latest copy of the file.This is called as auto versioning.

     Ex:<cfset  lstModified = getfileInfo("c:\test_prj\js\global.js").lastmodified >
     <cfoutput>
          <script type="text/javascript" src="a.js?v=#lstModified #"></script>
     </cfoutput>

It looks like a better solution, still there are some issues with this approach.
As per Google Caching Best Practices , It says not to use a query string with static file names,because it does not use cache for those files.

Don’t include a query string in the URL for static resources. Most proxies, most notably Squid up through version 3.0, do not cache resources with a “?” in their URL. To enable proxy caching for these resources, remove query strings from references to static resources, and instead encode the parameters into the file names themselves.

So what is the best solution?

So the best solution to auto version js/css/image files involves two steps.

  1. Append the last modified date time with the file name itself .
  2. Set up redirect rule on the server. The redirect rule is to redirect any files located in our \scripts\ or \css\ folders with version numbers in between the file name and the extension back to just the filename and extension. For example, I could now rewrite the url “/css/structure.css: as “/css/structure.1234.css” and Apache/IIS would see those as the exact same files. This approach is used by most of the high traffic sites like Amazon, Google etc.

So now in this way each time we modify some js/css/image file, we just do not need to change anything else on the production server, It will automatically refresh only those files that are modified and even cache the files as there is no query string appended to the file names.

AutoVersioning files using ColdFusion:
It involves two steps,

Step1:
First we need to add these redirect rules.

For IIS: 
Add this to the web.config:
 <rewrite>
            <rules>
                <rule name="caching">
                    <match url="^(.*)([0-9]{10}\.)(css|js)$" />
                    <action type="Rewrite" url="{R:1}{R:3}" />
                </rule>
            </rules>
        </rewrite>
For Apache:
Add this to .htaccess:
RewriteRule ^(scripts|css)/(.+)\.(.+)\.(js|css)$ $1/$2.$4 [L]

Step2:

<cffunction name="autoVersion" access="public" output="true" returntype="string" >
    <cfargument name="fileName" type="string" required="true" >
    
    <cfset var absPath = expandPath("#ARGUMENTS.fileName#")>
    <cfif !fileExists(absPath)>
        <cfreturn fileName>
    </cfif>    
    
    <!--- get the last modified datetime of the file --->
    <cfset  lstModified = getfileInfo(absPath).lastmodified >
    
    <!--- get the unix timestamp --->    
    <cfset  mtime =  dateDiff("s", "January 1 1970 00:00", lstModified)>
    <cfset var fileNameWithTimestamp = listFirst(ARGUMENTS.fileName, '.') & '.' & mtime & '.' & listLast(ARGUMENTS.fileName, '.')>
    <cfreturn fileNameWithTimestamp>
    
</cffunction>    

<cfoutput>
    <html>
        <head>
            <link rel="stylesheet" href="#autoVersion('css/myStyle.css')#" />
        </head>
        <body>
            
        </body>
    </html>
</cfoutput>