View Single Post
Old 09-10-2007, 11:39 AM   #1 (permalink)
Karl
The Reckoner
Advanced Programmer Top Contributor 
 
Karl's Avatar
 
Join Date: Sep 2007
Posts: 437
Thanks: 22
Karl is on a distinguished road
Default Cross-Site Request Forgeries

Cross-Site Request Forgeries

Here's a short, concise article on CSRF. A cross-site request forgery (CSRF) is an attack that attempts to exploit an applications trust in a user.

For this article I want you to visualise the following scenario.

A library has setup an online booking system where users can reserve books online. However, reservations for books that are not picked up will incur a penalty. This is where a malicious user may decide to have some fun.

In order to reserve a book the user simply sends the following request to reserve.php

Code:
reserve.php?book=12345&duration=14
The query string above would tell reserve.php to reserve the book with the ID 12345 for 14 days. With this knowledge an attacker could easily cause mischief by providing users with a link to your website, ordering any book they see fit. For example, a user could create the following image link:

Code:
<img src=http://www.library.com/reserve.php?book=99999&duration=99 />
This simple yet subtle image would take a user straight to the library website and reserve the book 99999 for 99 days. Now, although in this case this wouldn’t achieve much more than annoying a few people, the potential damage of CSRF becomes apparent. If this was an online ordering system the user could have easily ordered many items under a different users account.

CSRF attacks do require the attackers to target users who are already logged in, however, with today’s websites logins are usually remembered for long periods of time so this usually isn’t a problem.

How to Protect Yourself

In order to combat CSRF you must determine whether a request is coming from a valid or malicious user. One common technique to achieve this is through the use of tokens. Let’s say, for example, that the following form is used to reserve a book:

Code:
<form method=”get” action=”reserve.php” enctype=”multipart/form-data”>
<input type=”text” name=”book” />
<input type=”text” name=”duration” />
<input type=”submit” value=”Book It!” />
</form>
Now, in order to protect this form, we should create a new hidden field and store a randomly generated token. For example:

Code:
<input type=”hidden” name=”token” value=”<?php echo $token ?>” />
Where $token would hold a randomly generated string. This token would also be stored in the user’s session or cookie. Then, on the reserve.php page we simply check the form token against the users token, if they match, we can assume the request is legitimate. If they don’t match then we assume that it’s an illegal request and we force the user to login again.
Karl is offline  
Reply With Quote