yretuta yretuta - 3 years ago 72
PHP Question

preventing csrf in php

  1. Requiring authentication in GET and
    POST parameters, not only cookies;

  2. Checking the HTTP Referer header;

saw this post on wikipedia and was wondering how I can apply them

ok...I am using the Kohana PHP framework and I have the facility to determine the referrer header, but what exactly do I check in the referrer header? the framework function only returns the URL of the referrer

and how do I validate GET and POST params? against what? stored information? expected type?

Answer Source

To prevent CSRF you'll want to validate a one-time token, POST'ed and associated with the current session. Something like the following . . .

On the page where the user requests to delete a record:


 $token= md5(uniqid());
 $_SESSION['delete_customer_token']= $token;
<form method="post" action="confirm_save.php">
 <input type="hidden" name="token" value="<?php echo $token; ?>" />
Do you really want to delete?
<input type="submit" value=" Yes " />
<input type="button" value=" No " onclick="history.go(-1);" />

Then when it comes to actually deleting the record:


 $token = $_SESSION['delete_customer_token'];
 if ($token && $_POST['token']==$token) {
   // delete the record
 } else {
   // log potential CSRF attack.

The token should be hard to guess, unique for each delete request, accepted via $_POST only and expire after a few minutes (expiration not shown in this example).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download