Jump to content

CSRF token validation


jmb272

Recommended Posts

Hi guys.

 

I'm writing my own MVC framework and I've written a CSRF token validation class to help prevent CSRF attacks.

This is my first attempt at writing a CSRF token validation class and I just wanted to get some feedback.

 

I've looked at how others have done it and sort of stuck to the general route that most people take when writing something similar.

 

<?php

// Security measure.
if (!defined('BASE_PATH')) { exit(); }

class CSRF
{
private static $tokens = array();
private static $session_name = 'csrf_data';

/**
 * Loads CSRF token data from session into $tokens array.
 *
 * This method is called in the index.php file before a controller is loaded.
 *
 * @return void
 */
public static function init()
{
	$session_name = self::$session_name;

	// Move CSRF token data from session to class field.
	if (isset($_SESSION[$session_name])) {
		self::$tokens = unserialize($_SESSION[$session_name]);	
		unset($_SESSION[$session_name]);
	}
}

/**
 * Saves the CSRF data to a session.
 *
 * @static
 * @return void
 */
private static function save() 
{
	$session_name = self::$session_name;
	unset($_SESSION[$session_name]);

	$_SESSION[$session_name] = serialize(self::$tokens);
}

/**
 * Creates a new token.
 *
 * @static
 * @param string $name
 * @return string
 */
private static function generateToken($name)
{
	$token = md5(uniqid(rand(), true));

	self::$tokens[$name] = $token;
	self::save();

	return $token;
}

/**
 * Validate a token by its name.
 *
 * @static
 * @param string $name
 * @param string $token The CSRF token included with the form data.
 * @return bool
 */
public static function validateToken($name, $token)
{
	if (!isset(self::$tokens[$name])) {
		return false;
	}

	return ($token == self::$tokens[$name]);
}


} // End of CSRF class.

Edited by jmb272
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...