Search the Community
Showing results for tags 'cross-site request forgery'.
-
hey guys, i was introuduced the the world of csrf a little while ago by a member of PHP Freaks, beofore hand i had'nt a clue...so i decided to read a little more into and created a class to deal with generating tokens and ensuring the site is free from CSRF. now my understanding is that a CSRF can be made from clicking on sponsers, images and basically anything that can cause a request to another site/domain. now with the script allows the user to have multipule tokens and a new token is generated everytime when filling a form or whatever, allowing user to have more than one tab open. I'm just a little concerned that a CSRF attack can still be made this way as a new token is made on each form page. when creating a form i do this: <input name="csrf_token" type="hidden" value="12345" /> then on post im able to do something like this: $token = $csrf->get_token(); // token for input if ($csrf->is_safe($post->csrf_token) && form->is_valid()) { echo "safe" } else { echo "unsafe"; } here is my class <?php namespace Security; use Session\Session as Session; use Security\SSL; class CSRF { protected $_expiration = "3600"; public function get_token($expiration = null) { $ssl = new SSL; $token = $ssl->random_string(20); $session = new Session; $session->start(); if ($expiration === null) { $expiration = $this->_expiration; } else if (!is_numeric($expiration)) { // error } if (!$session->offset_exists('csrf_token')) { $session->csrf_token = array(); } $expiration = time() + $expiration; $session->append('csrf_token', array('token' => $token, 'expiration' => $expiration )); return $csrf_token; } protected function token_exists($token) { $session = new Session; $session->start(); $csrf_token = $session->csrf_token; $result = false; foreach ($csrf_token as $key => $array) { if (time() > $array['expiration']) { $session->offset_unset('csrf_token', $key); } else if ($array['expiration'] > time()&& $array['token'] === $token) { $session->offset_unset('csrf_token', $key); $result = true; } } return $result; } public function is_safe($token) { if ($this->token_exists($token)) { return true; } return false; } } any advise would be greatful, thank you