-
Notifications
You must be signed in to change notification settings - Fork 21
/
CSRF_Protect.php
115 lines (104 loc) · 2.14 KB
/
CSRF_Protect.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
<?php
/**
* A simple CSRF class to protect forms against CSRF attacks. The class uses
* PHP sessions for storage.
*
* @author Raahul Seshadri
*
*/
class CSRF_Protect
{
/**
* The namespace for the session variable and form inputs
* @var string
*/
private $namespace;
/**
* Initializes the session variable name, starts the session if not already so,
* and initializes the token
*
* @param string $namespace
*/
public function __construct($namespace = '_csrf')
{
$this->namespace = $namespace;
if (session_id() === '')
{
session_start();
}
$this->setToken();
}
/**
* Return the token from persistent storage
*
* @return string
*/
public function getToken()
{
return $this->readTokenFromStorage();
}
/**
* Verify if supplied token matches the stored token
*
* @param string $userToken
* @return boolean
*/
public function isTokenValid($userToken)
{
return ($userToken === $this->readTokenFromStorage());
}
/**
* Echoes the HTML input field with the token, and namespace as the
* name of the field
*/
public function echoInputField()
{
$token = $this->getToken();
echo "<input type=\"hidden\" name=\"{$this->namespace}\" value=\"{$token}\" />";
}
/**
* Verifies whether the post token was set, else dies with error
*/
public function verifyRequest()
{
if (!$this->isTokenValid($_POST[$this->namespace]))
{
die("CSRF validation failed.");
}
}
/**
* Generates a new token value and stores it in persisent storage, or else
* does nothing if one already exists in persisent storage
*/
private function setToken()
{
$storedToken = $this->readTokenFromStorage();
if ($storedToken === '')
{
$token = md5(uniqid(rand(), TRUE));
$this->writeTokenToStorage($token);
}
}
/**
* Reads token from persistent sotrage
* @return string
*/
private function readTokenFromStorage()
{
if (isset($_SESSION[$this->namespace]))
{
return $_SESSION[$this->namespace];
}
else
{
return '';
}
}
/**
* Writes token to persistent storage
*/
private function writeTokenToStorage($token)
{
$_SESSION[$this->namespace] = $token;
}
}