Jump to content

Recommended Posts

Posted (edited)

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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...