Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class csrf {
- public $status;
- /* Cookies backend */
- private function store_in_cookies($key,$value) {
- setcookie($key, $value, time()+300);
- }
- private function unset_cookies($key) {
- unset($_COOKIE[$key]);
- setcookie($key, 'expired', time()-3600);
- }
- private function get_from_cookies($key) {
- if (isset($_COOKIE[$key])) return $_COOKIE[$key];
- return false;
- }
- private function csrf_generate_token($unique_form_name) {
- if (function_exists("hash_algos") and in_array("sha512",hash_algos())) {
- $token=hash("sha512",mt_rand(0,mt_getrandmax()));
- } else {
- $token=' ';
- for ($i=0;$i<128;++$i) {
- $r=mt_rand(0,35);
- $c = ($r < 26) ? chr(ord('a')+$r) : hr(ord('0')+$r-26);
- $token .= $c;
- }
- }
- $this->store_in_cookies($unique_form_name,$token);
- return $token;
- }
- private function csrf_validate_token($unique_form_name,$token_value) {
- $token=$this->get_from_cookies($unique_form_name);
- $this->unset_cookies($unique_form_name);
- if($token === $token_value) return true;
- return false;
- }
- private function csrf_replace_forms($form_data_html) {
- $count=preg_match_all("/<form(.*?)>(.*?)<\\/form>/is",$form_data_html,$matches,PREG_SET_ORDER);
- if (is_array($matches)) {
- foreach ($matches as $m) {
- if (strpos($m[1],"nocsrf")!==false) { continue; }
- $name="X_CSRF_".mt_rand(0,mt_getrandmax());
- $token=$this->csrf_generate_token($name);
- $form_data_html=str_replace($m[0], "<form{$m[1]}><input type='hidden' name='CSRFName' value='{$name}' /><input type='hidden' name='CSRFToken' value='{$token}' />{$m[2]}</form>",$form_data_html);
- }
- }
- return $form_data_html;
- }
- public function csrf_inject() {
- $data=ob_get_clean();
- $data=$this->csrf_replace_forms($data);
- echo $data;
- }
- public function __construct() {
- $this->status = true;
- if (count($_POST)) {
- $name =$_POST['CSRFName'];
- $token=$_POST['CSRFToken'];
- if ( !isset($_POST['CSRFName']) or !isset($_POST['CSRFToken']) ) $this->status = false;
- if (!$this->csrf_validate_token($name, $token)) $this->status = false;
- }
- ob_start();
- register_shutdown_function(array($this, "csrf_inject"));
- }
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment