Security Protection Mechanisms to Safeguard Web Applications

Hello everyone! In this article, we are going to look about Cross-site Request Forgery (CSRF) and the preventing mechanisms. So, what is CSRF?? It is an attack that occurs in the user’s web browser where a mail, a malicious URL or an instant messaging performs an unwanted action in which the user is currently authenticated. This attack happens without the user’s consent so that the attacker can carry out the unauthorized transaction.

How does CSRF work?

There are several ways an attacker can steal the information from the user. The attack can be done in either of the following ways.

·         Exploiting URLs by using HTTP methods
Let’s say Peter wants to deposit Rs. 10,000 to Sam’s account. He will sign into his account and fill out all the details. Then, there will be a GET request with all the parameters as shown below.

 GET http://AbcBankingSolutions.com/deposit?account=Sam&amount=10000 HTTP/1.1

Now, the attacker John wants to exploit this URL and transfer Rs. 100,000 to his account. So, he gets the URL and modifies like given below.

 GET http://AbcBankingSolutions.com/deposit?account=John&amount=100000 HTTP/1.1
This request will get executed and Rs. 100,000 will be transferred to the attacker’s account. This attack is possible with other HTTP methods too.

·         Executing an action using social media
An attacker can create a normal webpage and make the victim view it. In that page, there might be links to click on them. The link may look like this,

<a href="http://AbcBankingSolutions.com/deposit?account=John&amount=100000">
View my Pictures!</a>

This link will show the victim some images. However, once he clicks the link, it will transfer money to the attacker’s account without the user’s consent. Sometimes, the page can have an invisible fake image which is designed to execute the attacker’s actions.

<img src="http:// AbcBankingSolutions.com/deposit?account=John&amount=100000 width="0" height="0" border="0">


Characteristics of CSRF

The following are the common characteristics of CSRF.
·         CSRF involves sites that have high user identification
·         Trust of that site is exploited by CSRF
·         It tricks the browser to perform its own requests
·         It involves HTTP requests that have side effects.

Preventing mechanisms

There are several ways to defend against CSRF attacks. In order to protect against these attacks, there should be a second check which has custom defence mechanisms using CSRF specific tokens to validate the requests sent by the user. The following are some of the common preventing mechanisms for CSRF attacks.

1.      Synchronizer Token Pattern
2.      Double Submit Cookies Pattern
3.      Encrypted Token Pattern
4.      Custom Header

In this blog, we are going to look how to implement Synchronizer Token Pattern and Double Submit Cookies Pattern.

Synchronizer Token Pattern
In this method, a CSRF token is created and mapped with the session cookie in the server side. When there are sensitive server-side operations, this token is included and then verified by the server to check the existence and correctness of it.


A web application is created using Servlet and deployed in GlassFish Server. The user has to login to the application from this form.


The server checks the validity of the authentication. If the correct credentials are provided, then a session ID will be generated. A cookie is created with the username, and sessionID is stored to it.

HttpSession session = request.getSession(true);
sessionHandler handler = new sessionHandler();
handler.setSession(session);
handler.setUsername(user);

Cookie ck = new Cookie(user, session.getId());
response.addCookie(ck);
handler.generateToken();
           

Now, the user will be redirected to the "Contact Us" form.


When this page loads contactUs.jsp file will invoke the stored CSRF token.

<% String token = sessionHandler.getCsrfToken();%>

Then, this token is added as a hidden field to the form so that the server can validate it.

<input  type="hidden" name="csrfToken" value="<%=token%>" class="form-control">         

The process.java file will get the CSRF token that is submitted through the form. It also gets the cookie created for that session and retrieves the stored CSRF token value. Now, both the received CSRF token and stored CSRF token will be compared. If both match, then a success message is shown.

String receivedToken = request.getParameter("csrfToken");
        
Cookie[] cookies = request.getCookies();
if (cookies != null) {
    for (Cookie cookie : cookies) {
         if (cookie.getName().equals("admin")) {
             sessionId = cookie.getValue();
         }
    }
 }
        
String token = sessionHandler.getCsrfTokenForSession(sessionId);
        
if (receivedToken.equals(token)) {
     out.println("<h1>Thankyou for the feedback!! </h1>")
} else {
     out.println("<h1>You are not a valid user!! </h1>");
}


In this way, it is not possible for an attacker to steal the information. However, saving the CSRF token in the server side and validating it, is costly and might drop the performance. To solve this issue, Double Submit Cookies Pattern can be used.

Double Submit Cookies Pattern
In this method, the CSRF token is generated when creating the session and stored as a cookie in the browser. The form will get the CSRF cookie and add as hidden value for making the request. Then, the server will validate the session and the CSRF token.

When the user logins to the system, the session ID is created and stored as a cookie with the username. Along with that, CSRF token is also generated and stored as a cookie in the browser.
HttpSession session = request.getSession(true);
sessionController controller = new sessionController();
controller.setSession(session);
 
Cookie sessionCookie = new Cookie(user, session.getId());
response.addCookie(sessionCookie);
controller.generateToken();
String token = sessionController.getCsrfToken();
Cookie tokenCookie = new Cookie("csrf", token);
response.addCookie(tokenCookie);
   

The CSRF cookie is called when loading the subscriber form using Javascript. The value of this cookie is added as a hidden field in this form.

<script type="text/javascript">
function getCookie() {
         var name = "csrf";
         var value = "; " + document.cookie;
         var parts = value.split("; " + name + "=");
         if (parts.length == 2)
            document.getElementById("csrf").value = parts.pop().split(";").shift();
      }
</script>
</head>
 
<body onload="getCookie()">
.
.
.
<input type="hidden" name="csrf" id="csrf">


Now, the server will receive this token and retrieve the CSRF cookie, and checks for validity. If both the values match, then a success message is displayed.

String receivedToken = request.getParameter("csrf");
       
String token = "token";
Cookie[] cookies = request.getCookies();
if (cookies != null) {
    for (Cookie cookie : cookies) {
         if (cookie.getName().equals("csrf")) {
             token = cookie.getValue();
         }
    }
}
 
if (receivedToken.equals(token)) {
    out.println("<h1>Thankyou for the subscription!! </h1>");
} else {
    out.println("<h1>You are not a valid user!! </h1>");
}

From this method, the server doesn’t need to save any CSRF token value. Also, since the cookie value and the form value must be the same, the attacker will be unable to successfully force the submission of a request with the random CSRF value.

Best Practices

Apart from these mechanisms, it is recommended for the users to follow these best practices to avoid unauthorized entries attacking the system.

·         After using a web application, log out from it
·         Do not allow browsers to save your username and password
·         Avoid using the same browser when accessing sensitive information
·         The use of plugins such as No-Script makes POST based CSRF vulnerabilities difficult to exploit.


The source code of the above two applications is available here.


Comments

Popular posts from this blog

Viewing Github profile using OAuth in Java

How to setup GitHub using SourceTree?