From 0d722f98d5fcb038de1d8a567b0db61fd1442241 Mon Sep 17 00:00:00 2001 From: Ben Roberts Date: Mon, 16 Jan 2012 00:18:44 +0000 Subject: [PATCH] Add a CSRF verification class --- source/lib/SihnonFramework/CSRF.php | 47 +++++++++++++++++++ .../lib/SihnonFramework/Exceptions.class.php | 3 ++ 2 files changed, 50 insertions(+) create mode 100644 source/lib/SihnonFramework/CSRF.php diff --git a/source/lib/SihnonFramework/CSRF.php b/source/lib/SihnonFramework/CSRF.php new file mode 100644 index 0000000..30fd024 --- /dev/null +++ b/source/lib/SihnonFramework/CSRF.php @@ -0,0 +1,47 @@ +session = $main->session(); + + $this->prepareSession(); + } + + public function prepareSession() { + if ( ! $this->session->exists('csrf')) { + $this->session->set('csrf', uniqid(), true); + } + } + + public function generate() { + $key = uniqid(); + $check = $this->generateCheck($key); + + return "{$key}:{$check}"; + } + + protected function generateCheck($key) { + return sha1($key . $this->session->get('csrf')); + } + + public function validate($token) { + list($key, $check) = explode(':', $token); + if ($check != $this->generateCheck($key)) { + throw new SihnonFramework_Exception_CSRFVerificationFailure(); + } + + return true; + } + + public function validatePost() { + $token = SihnonFramework_Main::issetelse($_POST['csrftoken'], 'SihnonFramework_Exception_CSRFVerificationFailure'); + return $this->validate($token); + } + +} + +?> \ No newline at end of file diff --git a/source/lib/SihnonFramework/Exceptions.class.php b/source/lib/SihnonFramework/Exceptions.class.php index 4dfe670..5834981 100644 --- a/source/lib/SihnonFramework/Exceptions.class.php +++ b/source/lib/SihnonFramework/Exceptions.class.php @@ -57,4 +57,7 @@ class SihnonFramework_Exception_LDAPConnectionFailed extends SihnonFramework_E class SihnonFramework_Exception_LDAPSecureConnectionFailed extends SihnonFramework_Exception_LDAPException {}; class SihnonFramework_Exception_LDAPBindFailed extends SihnonFramework_Exception_LDAPException {}; +class SihnonFramework_Exception_CSRFException extends SihnonFramework_Exception {}; +class SihnonFramework_Exception_CSRFVerificationFailure extends SihnonFramework_Exception_CSRFException {}; + ?>