Implementing Cross-site Request Forgery protection in a web application

Anne Deshani
7 min readMay 1, 2020

--

\_(ツ)_/¯༼ つ ◕_◕ ༽つ(•_•)☆*: .。. o(≧▽≦)o .。.:*☆\^o^/¯\_(ツ)_/¯

Today I am going to explain about the implementing Cross-site Request Forgery protection in web applications. First, let’s talk about the basic facts about the CSRF attack and its keywords.

WHAT IS A CSRF ATTACK ?

Cross Site Request Forgery is considered as one of top vulnerability in today’s web, where an untrusted website can force the user browser to send the unauthorized valid request to the trusted site. Legitimate user will lose his/her integrity over the website when the Cross site request forgery takes place.

By launching a successful CSRF attack against the authenticated user, an attacker is able to initiate arbitrary HTTP requests using the user credentials to the vulnerable web application. A successful CSRF attack effectively bypasses the underlying authentication mechanism and it can compromise the end user data and operation. If the victim account has administrator rights, this attack can compromise the entire web application.

CSRFs are typically conducted using malicious social engineering, such as an email or link that tricks the victim into sending a forged request to a server. As the unsuspecting user is authenticated by their application at the time of the attack, it’s impossible to distinguish a legitimate request from a forged one.

WHAT ARE CSRF TOKENS ?

A CSRF token is a unique, secret, unpredictable value that is generated by the server-side application and transmitted to the client in such a way that it is included in a subsequent HTTP request made by the client. When the later request is made, the server-side application validates that the request includes the expected token and rejects the request if the token is missing or invalid.

CSRF tokens can prevent CSRF attacks by making it impossible for an attacker to construct a fully valid HTTP request suitable for feeding to a victim user. Since the attacker cannot determine or predict the value of a user’s CSRF token, they cannot construct a request with all the parameters that are necessary for the application to honor the request.

  • The web server generates a token and stores it
  • The token is statically set as a hidden field of the form
  • The form is submitted by the user
  • The token is included in the POST request data
  • The application compares the token generated and stored by the application with the token sent in the request
  • If these tokens match, the request is valid
  • If these tokens do not match, the request is invalid and is rejected

WHAT IS AN AJAX CALL ?

Ajax call, which stands for Asynchronous JavaScript And XML, are becoming more popular as web applications look to bring in personalized items dynamically. AJAX calls are one method to load personalized content separately from the rest of the HTML document, which allows for the full HTML document to be cached, improving back end load time. AJAX calls have a wide range of applications but are particularly useful for websites who have a large amount of personal information which can prevent full HTML document caching. AJAX uses both a browser built-in XML Http Request object to get data from the web server and JavaScript and HTML DOM to display that content to the user. Despite the name “AJAX” these calls can also transport data as plain text or JSON instead of XML.

Session

A session creates a file in a temporary directory on the server where registered session variables and their values are stored. This data will be available to all pages on the site during that visit. A session ends when the user closes the browser or after leaving the site, the server will terminate the session.

Cookies

Cookies are text files stored on the client computer and they are kept of use tracking purpose. Server script sends a set of cookies to the browser. For example name, age, or identification number etc. The browser stores this information on a local machine for future use. When next time browser sends any request to web server then it sends those cookies information to the server and server uses that information to identify the user.

………………LET’S L👀👀K AT A SAMPLE PROJECT………………….`

This application is developed using PHP and HTML. First, you need to login to the application by entering username and password. The application is mainly consists of two pages which are login page and change password page. Now starting from the login page let’s discuss the implementation flow of the Synchronizer Token Pattern using this simple application.

First you need to login to the application by entering username and password which have been hard coded and validation happens by PHP in the back-end and using cancel button, you can cancel the submission at any time. You can enter user credentials as follows.

Username: Teddy

Password: password

If the user has given the correct credentials, he will be redirected to next page which is the change password page.

The 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. A session named teddy will be set for 10000ms when the login page loads and when the given credentials matches with the hardcoded credentials, a cookie will be generated on session id and token. If the credentials you entered are incorrect, you have to re-enter the credentials.

Here, after the user logged in, the browser will send an Ajax call to get the CSRF token. This Ajax call contains the session id. Then the server will response the corresponding CSRF token along with the response body. User doesn’t see this is happening when page loads. Session cookie is splitting by delimeters. The ajax call type is post and its URL is getdata.php

In Token.php file to generate csrf token, openssl_randon_pseudo_bytes() function is used. So, we should have openssl installed in order not to get an error. To have more security, the generated value then converted into it’s base64 value using base64_encode() function.

Then, we have to call the previously created static generate function in the hidden area of HTML which is hidden to the interface and randomly change when the browser refreshed and then this value is passing to welcome.php in POST method.

In the change password page, we can change the current password using the POST request. So, we have to give credentials username and new password. When we submit the values, the browser automatically validates the given credentials and the csrf token. When all validates right, it will return true. If not, it will return false.

When the password is changed a pop up box is shown as below.

The session become expired after you changed the password.

If try to refresh the browser again, token will be refreshed and the previous token become invalid.

Important : You cannot directly enter to welcome.php page.Because it is being set if the session username is not given, you cannot visit the page directly. So, it prevent from finding indexes of the page and redirect to log again.

You can find the full implementation of this sample application at, https://github.com/annedeshani/Project-WS.git (●'◡'●)

To know more about the CSRF attacks and its keywords, follow the folowing links… 😎

https://en.wikipedia.org/wiki/HTTP_cookie

--

--