From 03921f339e44ff5cb3ddcef0711b330af56ede5a Mon Sep 17 00:00:00 2001 From: minhaz Date: Fri, 6 Jun 2014 23:17:18 +0530 Subject: [PATCH] COOKIE logic shifted to SESSION logic #Modification: 1. validation now based on SESSION tokens 2. setCookie() function name changed to refeshToken() 3. refreshToken() now sets/modifies the token in session var 4. csrftoken is refreshed in case of true validation only 5. Expiry time of token in cookie now 30 minutes 6. init() sets session in case not set! --- libs/csrf/csrfprotector.php | 32 ++++++++++++++++++++++---------- 1 file changed, 22 insertions(+), 10 deletions(-) diff --git a/libs/csrf/csrfprotector.php b/libs/csrf/csrfprotector.php index 0cb28e8..a7b1aac 100644 --- a/libs/csrf/csrfprotector.php +++ b/libs/csrf/csrfprotector.php @@ -24,7 +24,7 @@ class csrfProtector * expiry time for cookie * @var int */ - public static $cookieExpiryTime = 300; //5 minutes + public static $cookieExpiryTime = 1800; //30 minutes /** * flag for cross origin/same origin request @@ -67,6 +67,11 @@ class csrfProtector */ public static function init($length = null, $action = null) { + //start session in case its not + if (session_id() == '') { + session_start(); + } + if (!file_exists(__DIR__ ."/../config.php")) { throw new configFileNotFoundException("configuration file not found for CSRFProtector!"); } @@ -89,6 +94,9 @@ public static function init($length = null, $action = null) // Initialize output buffering handler ob_start('csrfProtector::ob_handler'); + + if (!isset($_COOKIE[self::$tokenName])) + self::refreshToken(); } /** @@ -111,29 +119,28 @@ public static function authorisePost() //currently for same origin only if (!(isset($_POST[CSRFP_POST]) && isset($_COOKIE[self::$tokenName]) - && ($_POST[CSRFP_POST] === $_COOKIE[self::$tokenName]) + && ($_POST[CSRFP_POST] === $_SESSION[self::$tokenName]) )) { //action in case of failed validation self::failedValidationAction(); + } else { + self::refreshToken(); //refresh token for successfull validation } } else if (!static::isURLallowed()) { //currently for same origin only if (!(isset($_GET[CSRFP_POST]) && isset($_COOKIE[self::$tokenName]) - && ($_GET[CSRFP_POST] === $_COOKIE[self::$tokenName]) + && ($_GET[CSRFP_POST] === $_SESSION[elf::$tokenName]) )) { //action in case of failed validation self::failedValidationAction(); + } else { + self::refreshToken(); //refresh token for successfull validation } - } - - /** - * Refresh cookie for each request - */ - self::setCookie(); + } } /** @@ -196,9 +203,14 @@ private static function failedValidationAction() * @param: void * @return void */ - public static function setCookie() + public static function refreshToken() { $token = self::generateAuthToken(); + + //set token to session for server side validation + $_SESSION[self::$tokenName] = $token; + + //set token to cookie for client side processing setcookie(self::$tokenName, $token, time() + self::$cookieExpiryTime);