I have a PHP based document management system that I wrote a while back to store my families paperwork. Although the full code is not publicly available it would still be a good idea to protect it against CSRF attacks.
Would this be a suitable solution for implementing sitewide CSRF protection:
All forms are protected against being directly accessed, so they all have to be accessed via index.php, this is done with the following code at the top of each form PHP file:
if(basename(__FILE__) == basename($_SERVER['PHP_SELF'])){
header("Location: ../../");
}
In the index.php file, which every form must go through to be accessed I have the following code to create a token session if it doesn't exist and then check for any post data containing a token (this is done before any possible calls to a form):
// Generate session token for CSRF
if (empty($_SESSION['token'])) {
$_SESSION['token'] = bin2hex(random_bytes(32));
}
if (isset($_POST['token'])) {
if (!hash_equals($_SESSION['token'], $_POST['token'])) {
echo 'There is a problem with your session token.';
exit;
}
}
Form validation contains the following code to check that a token session has been set to ensure the session checking on index.php has been ran:
if (isset($_POST['token']) && $_POST['token'] == $_SESSION['token']) {
// Process form data
}
Finally, each form would include a hidden element like so:
<input type="hidden" name="token" value="<?php echo $_SESSION['token']; ?>" />
As far as I can see this should be suitable, but I am not an expert on CSRF PHP attacks.
My questions are:
1) Is the first block of code a suitable method of blocking access to the file, other than being included in another PHP file on the same server?
2) Is this method of implementing a token suitable to stop CSRF attacks?