2016-01-02 17:55:31 +00:00
|
|
|
<?php
|
2016-02-03 22:22:56 +00:00
|
|
|
/**
|
|
|
|
* Holds the CSRF token handler.
|
2016-03-08 23:07:58 +00:00
|
|
|
*
|
2016-02-03 22:22:56 +00:00
|
|
|
* @package Sakura
|
|
|
|
*/
|
|
|
|
|
2016-01-02 17:55:31 +00:00
|
|
|
namespace Sakura;
|
|
|
|
|
|
|
|
/**
|
2016-02-02 21:04:15 +00:00
|
|
|
* Used to generate and validate CSRF tokens.
|
2016-03-08 23:07:58 +00:00
|
|
|
*
|
2016-01-02 17:55:31 +00:00
|
|
|
* @package Sakura
|
2016-02-02 21:04:15 +00:00
|
|
|
* @author Julian van de Groep <me@flash.moe>
|
2016-01-02 17:55:31 +00:00
|
|
|
*/
|
|
|
|
class CSRF
|
|
|
|
{
|
2016-02-02 21:04:15 +00:00
|
|
|
/**
|
|
|
|
* The prefix to prevent collisions in the $_SESSION variable.
|
|
|
|
*/
|
2016-01-02 17:55:31 +00:00
|
|
|
const ID_PREFIX = '_sakura_csrf_';
|
2016-02-02 21:04:15 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* The size of the randomly generated string.
|
|
|
|
*/
|
2016-01-02 17:55:31 +00:00
|
|
|
const RANDOM_SIZE = 16;
|
|
|
|
|
2016-02-02 21:04:15 +00:00
|
|
|
/**
|
|
|
|
* Create a new CSRF token.
|
2016-03-08 23:07:58 +00:00
|
|
|
*
|
2016-02-02 21:04:15 +00:00
|
|
|
* @param mixed $id The ID for this token.
|
2016-03-08 23:07:58 +00:00
|
|
|
*
|
2016-02-02 21:04:15 +00:00
|
|
|
* @return string The token.
|
|
|
|
*/
|
2016-01-02 17:55:31 +00:00
|
|
|
public static function create($id)
|
|
|
|
{
|
|
|
|
// Generate a token
|
|
|
|
$token = self::generate();
|
|
|
|
|
|
|
|
// Make identifier
|
|
|
|
$id = strtoupper(self::ID_PREFIX . $id);
|
|
|
|
|
|
|
|
// Assign to session
|
|
|
|
$_SESSION[$id] = $token;
|
|
|
|
|
|
|
|
// Return the token
|
|
|
|
return $token;
|
|
|
|
}
|
|
|
|
|
2016-02-02 21:04:15 +00:00
|
|
|
/**
|
|
|
|
* Generate a CSRF token.
|
2016-03-08 23:07:58 +00:00
|
|
|
*
|
2016-02-02 21:04:15 +00:00
|
|
|
* @return string Cryptographically secure random string.
|
|
|
|
*/
|
2016-01-02 17:55:31 +00:00
|
|
|
public static function generate()
|
|
|
|
{
|
2016-07-29 19:31:36 +00:00
|
|
|
return bin2hex(random_bytes(self::RANDOM_SIZE));
|
2016-01-02 17:55:31 +00:00
|
|
|
}
|
|
|
|
|
2016-02-02 21:04:15 +00:00
|
|
|
/**
|
|
|
|
* Validate a CSRF token.
|
2016-03-08 23:07:58 +00:00
|
|
|
*
|
2016-02-02 21:04:15 +00:00
|
|
|
* @param mixed $token The token.
|
|
|
|
* @param mixed $id The ID.
|
2016-03-08 23:07:58 +00:00
|
|
|
*
|
2016-02-02 21:04:15 +00:00
|
|
|
* @return bool Indicator if it was right or not.
|
|
|
|
*/
|
2016-01-02 17:55:31 +00:00
|
|
|
public static function validate($token, $id)
|
|
|
|
{
|
|
|
|
// Set id
|
|
|
|
$id = strtoupper(self::ID_PREFIX . $id);
|
|
|
|
|
|
|
|
// Check if the token exists
|
|
|
|
if (!array_key_exists($id, $_SESSION)) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2016-07-29 19:31:36 +00:00
|
|
|
return hash_equals($token, $_SESSION[$id]);
|
2016-01-02 17:55:31 +00:00
|
|
|
}
|
|
|
|
}
|