Stopping CSRF Attacks in Your PHP Applications - Fixing the Vulnerability
(Page 2 of 2 )
So, how do you fix it? The most common method of fixing this is to utilize a site token that identifies a request as coming from your site. It is relatively simple to implement and will certainly save you tons of grief. The theory behind it is simple: create a unique token, associate it with the user, and then pass it along with the form. If the token doesn't check out, don't take action on the request. So, our original form would look like this:
<?php
if(!is_logged_in()) {
// redirect to login page
exit;
}
$token = md5(uniqid(rand(), TRUE));
$_SESSION['token'] = $token;
?>
<form method="get" action="updateemail.php">
<input type="text" name="newemail" />
<input type="hidden" name="sitetoken" value="<?php echo $token; ?>" />
<input type="submit" name="submit" value="Submit" />
</form>
Then the updateemail.php script would look like this:
<?php
if(!is_logged_in()) {
// redirect to login page
exit;
}
if($_SESSION[‘token'] != $_GET[‘sitetoken']) {
echo "Not a valid request!"; exit;
}
update_email();
echo "Your email address has been updated.";
?>
I like fixes like this…quick and simple. You should be able to go through your web application and plug up any holes relatively quickly. Well, I hope that this short article has helped you to see the danger of CSRF attacks and how you can easily stop them from happening. Do you have any other techniques you use to avoid these attacks? If so, please share them!
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |