Skip to content

Commit

Permalink
COOKIE logic shifted to SESSION logic
Browse files Browse the repository at this point in the history
#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!
  • Loading branch information
mebjas committed Jun 6, 2014
1 parent 07699c1 commit 03921f3
Showing 1 changed file with 22 additions and 10 deletions.
32 changes: 22 additions & 10 deletions libs/csrf/csrfprotector.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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!");
}
Expand All @@ -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();
}

/**
Expand All @@ -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();
}
}

/**
Expand Down Expand Up @@ -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);
Expand Down

0 comments on commit 03921f3

Please sign in to comment.