Wednesday, September 5, 2018


Synchronizer Token Pattern

Previously in my last blog post (Cross Site Request Forgery) I discussed about what is CSRF attack on Web Applications and today I am going to explain the Synchronizer Token Pattern in this blog post as one of the identified solutions for this CSRF security attack. 

Now let's assume all the state changing operations are done through POST, PUT, DELETE requests and anyway session cookie is going with these requests. But assume we expect user to send some specific token along with the request and only if that token is received Facebook server will validate the token and allow the request to be processed.

Synchronizer Token Pattern is used this security token method to prevent form the CSRF attack on Web Applications. Following diagram will simply show how this security pattern works.


As the diagram shows, let's say John needs to log in to Facebook and he enters his account credentials (username and password). After John entering his credentials, server will authenticate the user and create a Session Id for the particular session. Additionally what happens in Synchronizer Token Pattern is, server generates a random token which we call as a CSRF token. At the login process server will generate, store and keep this token at server side in the user session. Browser even does not know anything about this CSRF token. Only Session Id will come along with the session cookie and store at the browser's cookie storage.

Now user is logged in successfully and browser has the session id. Let say John wants to update his status on Facebook and he browses that update status page. Then this request is sent to the sever and there the session cookie goes, so server knows that is john who is logged in.Then server sends the response updateStatus.html page in return. 


Now what happens is, let say that HTML page has some text box and a button where user can type the status and clicks on the button, that will send a POST request for getting the status updated. When that HTML page get rendered in the browser, internally this page knows that it has a form and some JavaScript (JS). That JavaScript knows there is a HTML form and user will make some POST request. So, what that JS does is, when this page loads in the browser, that will make an Ajax request to some URL (facebook.com/getToken) in the website. This Ajax call contains the session cookie. Hence along with that request session id will go because the path and domain is matched. So server knows this is a valid user who is making the request after checking the session id. Then server will send the corresponding CSRF token along with the response of that Ajax call. This whole process is done by JS embedded into the page.


When JS receives the CSRF token, it modifies the DOM (Document Object Model), get the source and embed a hidden field on from submit. User doesn't see this is happening when page loads. So, user types the status and click on the submit button. It will send another POST request to update the status of the page. With this request, session cookie, status value in the body and the CSRF token also go. Now server receives this request. Whenever POST, PUT or DELETE request comes server knows that it needs to protect the token. So first server will check the cookie is received in the header. Then server checks is it a legitimate cookie or John is a valid user. After that it checks the request body and get the CSRF token. Then sever checks if that token matches with the previously stored session's token. If it matches only John is a legitimate, the request will be satisfied and status will get update. Simply this is how Synchronizer Token Pattern works on Web Applications.


Will an attacker able to perform this?? 

In a scenario like, if the attacker creates his own website (e.g. attacker.com) would attacker be able to make an AJAX call and get the CSRF token ? From attacker.com to facebook.com/getToken, is a cross domain AJAX call where actual user and attacker in two different domains. By default cross domain AJAX calls are not possible. So this attackers's call will fail and an attacker will not be able to obtain the CSRF token. Since the token is unavailable in the request body, the server will not complete the action. Therefore CSRF is prevented.

Now lets move into the sample application developed for explain this security pattern.

Sample Application

This sample application is developed using PHP and you can find the uploaded Github source code from here
The application is mainly consists of three main screens which are login page, update status page and updated results page. Now starting from the login page let's discuss the implementation flow of the Synchronizer Token Pattern using this simple application.

The login page is as follows. First you need to login to the application by entering username and password. For the demonstration purpose here I have hard coded the credentials. You can enter user credentials as follows.

Username: admin
Password : admin


index.html

This login form submits user credentials through a POST method. At the login process, if the user is authenticated, unique Session Id  and the CSRF token will be created along with this session. Upon login, generated session identifier set as a cookie in the browser and at the same time, this CSRF token is stored against the session identifier at server side. For the demonstration purpose here I store CSRF token in a text file called Token.txt. 






























































































updateStatus.html

Here, what internally happens is, updateStatus.html contains the simple PHP code snippets to validate the user credentials. Then it makes an Ajax call to generate the CSRF token to csrf_token_generator.php. This Ajax call contains the session id and upon the Ajax call, server will send the corresponding CSRF token along with the response. This is where token embeds into a hidden field on form submit. User doesn't see this is happening when page loads. So, user types the status and click on the Update button. It will send another POST request to update the status of the page. 

In below screen you can observe the CSRF token value has been added to the hidden field when the form loads. 


























csrf_token_generator.php

This php file is used to generate the CSRF token and it sets corresponding the session id. Here, openssl_randon_pseudo_bytes() is used to generate the 32bit long csrf token. In order to use this function you have to have openssl installed. Otherwise it will give you an error. The generated value then converted into it's base64 value using base64_encode() function in order to make it more secure. 

The POST request that user makes to update the status contains this generated CSRF token and the session cookie. Then server checks the cookie header for session id and request body for get the CSRF token. 

Then server calls checkToken() function to confirm whether the token is matched or not with previously stored session's token. In this sample application token.php is contained this check function which takes csrf token and session id as two input parameters and return true if the received parameters are matching with the values that are stored previously in Token.txt.

token.php


Tokens.txt

To explain you to more, here I will show you two alerts containing the session id and CSRF token coming with the update status POST request. You can see those two are matching with session id and CSRF token stored inside the Token.txt. 




Now let's look at how we can observe updated status. Here, results.php is the place where this checkToken() function  is invoked and display the updated status upon the token validation.






results.php

You can find the full implementation of this sample application at,

https://github.com/TharakaMadushanki/Prevent-CSRF-Attack---Synchronizer-Token-Pattern

Drawback of the Synchronizer Token Pattern is server has to keep and store all the tokens.Imagine there are one billion of users, then the server storage needs to store one billion of record or even more, because one user can have multiple sessions. 

In my next blog post, I will be discussing how Double Submit Cookie pattern is used to prevent from the CSRF attack and you can find it from here.


Tuesday, September 4, 2018

Cross Site Request Forgery (CSRF)


Cross Site Request Forgery is a vulnerability and a common attack that tricks a user into executing an unwanted action (such as sending a link via chat) in a web application. CSRF attack can force the user to perform state changing requests or operations in systems like unfriend a friend in Facebook, upload a photo or status in Facebook, changing email addresses and so forth.

In this blog post I am discussing on what is CSRF attack and how we can prevent from this attack in web applications. In addition to that, I will be discussing on two major security patterns , which we can implement for preventing CSRF attack in my onfall blog posts.

What is CSRF?

There are few ways in which an end user can be tricked into loading information from or submitting information to a web application by attacker. Following diagram will simply explain to you what is CSRF by using a real-world example.





* session-id is used to identify the intended user

If the Facebook was designed to use GET request to unfriend a friend, the unfriend request looks like this:



Below I have explained the ways in which an end user can be tricked by the attacker with respect to the given example.

1. Building an exploit URL


As the diagram shows, let's say John needs to log in to his Facebook account. Normally what he does is he simply enters his Username and Password to get in on Facebook. After John entering his credentials on Facebook, it will authenticate John and create a Session Id for his new Session if only John is a valid user. Later on this session Id will be used to identify the John uniquely. This session Id will come along with the session cookie and store at the browser's cookie storage. 

Let's say John wants to unfriend Sam from his Facebook friend list. Simply he can go to the Facebook page and click on the link to unfriend the Sam. But imagine an attacker prepares that URL (shorten the URL using a URL shorter into https://goo.gl/124qa) to unfriend the Sam from John's account and send that link to the john via chat. 


Assume while you are browsing on Facebook you get a chat message from this Attacker. So, John does not know about that URL and he clicks on it. John's browser is making this request unintentionally (by converting that shorten URL into http://www.facebook.com/user/unfriend? id=Sam) and Sam will be removed from his Facebook account. This is how attacker tricks a user to into execute an unwanted action and this problem is known as the Cross Site Request Forgery.

2. Planting a fake image on page that is likely to be visited by the user

Let say attacker does not need to send this link through a chat to John. Attacker hosts a website (e.g. gossip.com) and in there attacker has this image element.

http://gossip.com

Attacker


Assume somehow John visits this gossip.com and when this page loads hidden image will be tried to get loaded. Since this is not an actual image and this contains the link for unfriend Sam fro the John's Facebook account, when this request fires from the John's browser unknowingly Sam will be removed from his Facebook account. This problem is known as the Cross-Site Request Forgery.

How we can prevent from CSRF attack?

As the fundamental rule of preventing from CSRF attack, never implement any state changing operations in the system through GET requests. State changing operation is any operation that modifies data or behavior of the system.

Modify data à update status, update cover photo in Facebook 

Modify behavior Ã  shutting down a server and sending it to a different state

Let's assume the Facebook now implements a POST request and the vulnerable request looks like this:


Anyone who sends a post request and if the session cookie comes along it will be accepted and then the data does not go as query parameter but in the body. So, can we solve this problem using a POST method instead of using GET method or attacker can still trick the user? Such a request cannot be delivered using a standard Anchor tags or Img tags as discussed earlier, but can be delivered using a FORM tag:

Now let say gossip.com has below form:









This form requires the user to click on the submit button, but this can be also executed automatically using JavaScript or some jQuery on page. So, still attacker can trick the user. The actual reason is the session cookie goes with the request. Because browser does not know whether this a legitimate user or an attacker, browser checks only the action. So, browser selects all eligible cookies to send along the request. Facebook also does not know whether this is an actual user or not (anyway it is actual user's browser) and Facebook will proceed that action. So, still we cannot solve this problem actually in this way.

So, to prevent from this CSRF attack security problem there are two major security patterns that we can implement. 
        
       1.   Synchronizer Token Pattern
       2.   Double Submit Cookie Pattern

 I will be discussing these security patterns in my next blog posts.

Wednesday, May 10, 2017

Maven as a Build Tool

Have you heard "Maven" before..?? I will explain to you it in a  way you can understand what is and why we have Maven.

When you are creating a project normally you need to add necessary supporting libraries. Have you experienced in having difficulties when you were doing this. Hope most of you will say the answer as "yes". 

Can we avoid those issues by having a tool which add all necessary libraries while you are building your project. The answer is obviously "yes". Because here you have Maven for do everything on behalf of you.



Maven makes Java programming easy..Although it referrers to as a build tool, but it is so much more that that.

We can use Maven to manage the entire lifecycle of our project in a way generating reports, and storing documents with its POM ( Project Object Model) repository. 

And it is not just for Java; C/C++, PHP, and Scala programmers can use Maven, too.

What is Maven..??
  • Maven is a "build management tool".
  •  Defines how our "*.java" files get compiled to "*.class" and  packaged into "*.jar" (or "*.war" or "*.ear") files.
  • Manages our CLASSPATH and all other tasks that are required to build our project. 
  • Similar to "Apache Ant" or "Gradle".
  • It attempts to be completely self-contained.
  • We don't need any additional tools for other common tasks like downloading & installing necessary libraries.
What are the main benefits of using maven ..??
  • We can get our package dependencies easily.
  •  Forces us to have a standard directory structure.
What are the Objectives of Maven..??
  • Making the build process easy.
  • Providing a uniform build system.
  • Providing quality project information.
  • Providing guidelines for best practices development.

Tuesday, May 2, 2017

Single-Page Applications (SPA)

You could find hundreds of reading stuffs about the single page application easily from the internet.But for the beginners  who are looking for get a basic idea about what is single page application, I hope you could get an clear idea from this blog. Here I have simply explained the basics of Single Page Application.
  • Let see simply what is SPA is..?
SPAs are web applications that load a single HTML page.
  • What is mean of "load a single HTML page"..?
That means we dynamically update that page when user interacts with the app.
  • How we can dynamically update the page..??
SPAs heavily use AJAX and HTML5 to create responsive Web apps, without constant page reloads. Simlpy it is the way we communicate with back-end servers without doing a full page refresh and get data loaded into our application. That means much of the work (process of rendering pages)  happenns on the client side.
  • Why we need SPA over regular website..??
Because in regular web app, every time when the application needs to display the data or need to submit data back to server it has to request a new page from the server and then render it in the web browser.

So why we cannot use this approach..??


With this approach nothing wrong if our application is a simple application. But when we need to create a rich user interface then our page might become very complex and we need to be loaded with lot of data.

Hence in this approach we need to ,

  • Generate complex pages on a server.
  • Transfer them to the client over internet.
  • Render them into the browser.
Because of these reasons it takes rime and degrade the user experience. So now have moved to SPAs with AJAX.
SPA allows refreshing only parts of the page when needs instead of reloading the whole page each time. It helps to improve the user experience since it is the way of reduced amount of pages refreshes. .

From the image I have put below, you could get a better picture in your mind about how SPA and regular app work.




Here are some advantages and disadvantages of SPA.

SPA advantages
  • Faster page loading time
  • Improved user experience
  • Decoupling front-end and back-end 
  • No need to write the code to render pages on server.
SPA disadvantages
  • Heavy client frameworks which are required to be loaded to the client

I hope you have got a basic understanding about single page application from here.


Friday, April 21, 2017

Checked and Unchecked exceptions

In java, there are two types of exceptions we can find.
  1.         Checked exceptions
  2.       Unchecked exceptions

Checked exception:

Checked exceptions are checked at the compilation time. If some code contains checked exception, that exception should be handled using try catch block or throw using throws keyword.

Example :

Let’s say in a java program we open a file and try to read it. In there we have to use FileReader(). FileReader() throws an exception called “FileNotFoundException” . and also I there we have to use readLine() and close() methods. Those are also throws checked exception called “IOException”.

Sample code :

            import java.io.*;

class Main {
    public static void main(String[] args) {
        FileReader file = new FileReader("C:\\test\\a.txt");
        BufferedReader fileInput = new BufferedReader(file);
         
        // Print first 3 lines of file "C:\test\a.txt"
        for (int counter = 0; counter < 3; counter++)
            System.out.println(fileInput.readLine());
         
        fileInput.close();
    }
}

Output :

               Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - 
unreported exception java.io.FileNotFoundException; must be caught or declared to be
thrown
         at Main.main(Main.java:5)

To fix this we have to use throws keyword or try-catch block.

Unchecked Exceptions :-

Unchecked exception are the exceptions which are not check in the compilation time. As an example, in C++, all exceptions are unchecked. So it is not forced by the compiler to handle or throw.

In Java, Errors and Run time Exception classes are unchecked. All others are checked.

Example :

                class Main {
   public static void main(String args[]) {
      int x = 0;
      int y = 10;
      int z = y/x;
  }
}

 Output :

        Exception in thread "main" java.lang.ArithmeticException: / by zero
         at Main.main(Main.java:5)
         Java Result: 1


Friday, April 7, 2017

AngularJS Directives

 What is AngularJS..??


  • Open-source web application framework. 
  • Library written in JavaScript.
  • Maintained by Google and an AngularJS community of developers. 
  • Distributed as a JavaScript file, and can be added to a web page with a <script> tag.
  • Assist with creating single-page applications. 
  • Require only HTML, CSS and JavaScript on the client side. 
  • Reads HTML for additional custom tag attributes. 
  • Extends HTML attributes with Directives which are in those custom attributes. 
  • Binds data (input output parts of the page) to HTML with expressions.

Note: 
To add angular to the web page , use below URL with script tag.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js">
</script>


As i mentioned you earlier AngularJS extends with Directives let's look at what are those Directieves.

AngularJS directives are HTML attributes with an "ng" prefix. Here are some directives.

  • ng-app - defines the root element of an AngularJS application and will automatically initialize the app when a web page is loaded.
  • ng-model - binds the value of HTML controls (input, select, textarea) to application data.
  • ng-bin - binds application data to the HTML view.
  • ng-init - defines initial values for an AngularJS application. 
  • ng-repeat - repeats an HTML element.
   To get an idea about how directives are used i will show you an example.   

    Example 1 :




     
Example 2:
    
Example 3:











 

Note:
Here i have put only the very basic directives.If you want to follow more  AngularJS directives refer this link.

Angular Applications

  • modules - deifne AngularJS applications using ng-app directive.
  • controllers - control AngularJS applications using ng-controller directive..

 Example 1: AngularJS Module

 Note :
       
 Example 2: AngularJS Controller



Example 3: 


Note : 
Normally we put module and the controllers in separate JavaScript  files (myApp.js , myController.js ) and link them using script tag .