/
class.xsrf.php
226 lines (197 loc) · 5.96 KB
/
class.xsrf.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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
<?php
if (!defined("__IN_SYMPHONY__")) {
die("You cannot directly access this file.");
}
/**
* @package toolkit
*/
/**
* The `XSRF` class provides protection for mitigating XRSF/CSRF attacks.
*
* @since Symphony 2.4
* @author Rich Adams, http://richadams.me
*/
class XSRF
{
/**
* Return's the location of the XSRF tokens in the Session
*
* @return string|null
*/
public static function getSessionToken()
{
$token = null;
if (isset($_SESSION[__SYM_COOKIE_PREFIX__]['xsrf-token'])) {
$token = $_SESSION[__SYM_COOKIE_PREFIX__]['xsrf-token'];
}
if (is_array($token)) {
$token = key($token);
}
return is_null($token) ? null : $token;
}
/**
* Adds a token to the Session
*
* @param array $token
*/
public static function setSessionToken($token = array())
{
$_SESSION[__SYM_COOKIE_PREFIX__]['xsrf-token'] = $token;
}
/**
* Removes the token from the Session
*
* @param string $token
*/
public static function removeSessionToken($token = null)
{
if (is_null($token)) {
return;
}
$_SESSION[__SYM_COOKIE_PREFIX__]['xsrf-token'] = null;
}
/**
* Generates nonce to a desired `$length` using `openssl` where available,
* falling back to using `/dev/urandom` and a microtime implementation
* otherwise
*
* @param integer $length optional. By default, 30.
* @return string
* base64 encoded, url safe
*/
public static function generateNonce($length = 30)
{
$random = null;
if ($length < 1) {
throw new Exception('$length must be greater than 0');
}
// Use the new PHP 7 random_bytes call, if available
if (!$random && function_exists('random_bytes')) {
$random = random_bytes($length);
}
// Get some random binary data from open ssl, if available
if (!$random && function_exists('openssl_random_pseudo_bytes')) {
$random = openssl_random_pseudo_bytes($length);
}
// Fallback to /dev/urandom
if (!$random && is_readable('/dev/urandom')) {
if (($handle = @fopen('/dev/urandom', 'rb')) !== false) {
$random = @fread($handle, $length);
@fclose($handle);
}
}
// Fallback if no random bytes were found
if (!$random) {
$random = microtime();
for ($i = 0; $i < 1000; $i += $length) {
$random = sha1(microtime() . $random);
}
}
// Convert to base64
$random = base64_encode($random);
// Replace unsafe chars
$random = strtr($random, '+/', '-_');
$random = str_replace('=', '', $random);
// Truncate the string to specified lengh
$random = substr($random, 0, $length);
return $random;
}
/**
* Creates the form input to use to house the token
*
* @return XMLElement
*/
public static function formToken()
{
// <input type="hidden" name="xsrf" value=" . self::getToken() . " />
$obj = new XMLElement("input");
$obj->setAttribute("type", "hidden");
$obj->setAttribute("name", "xsrf");
$obj->setAttribute("value", self::getToken());
return $obj;
}
/**
* This is the nonce used to stop CSRF/XSRF attacks. It's stored in the user session.
*
* @return string
*/
public static function getToken()
{
$token = self::getSessionToken();
if (is_null($token)) {
$nonce = self::generateNonce();
self::setSessionToken($nonce);
// Handle old tokens (< 2.6.0)
} elseif (is_array($token)) {
$nonce = key($token);
self::setSessionToken($nonce);
// New style tokens
} else {
$nonce = $token;
}
return $nonce;
}
/**
* This will determine if a token is valid.
*
* @param string $xsrf
* The token to validate
* @return boolean
*/
public static function validateToken($xsrf)
{
$token = self::getSessionToken();
return $token === $xsrf;
}
/**
* This will validate a request has a good token.
*
* @throws SymphonyErrorPage
* @param boolean $silent
* If true, this function will return false if the request fails,
* otherwise it will throw an Exception. By default this function
* will thrown an exception if the request is invalid.
* @return false|void
*/
public static function validateRequest($silent = false)
{
// Only care if we have a POST request.
if (count($_POST) > 0) {
if (!self::validateToken($_POST["xsrf"])) {
// Token was invalid, show an error page.
if (!$silent) {
self::throwXSRFException();
} else {
return false;
}
}
}
}
/**
* The error function that's thrown if the token is invalid.
*
* @throws SymphonyErrorPage
*/
public static function throwXSRFException()
{
$msg =
__('Request was rejected for having an invalid cross-site request forgery token.')
. '<br/><br/>' .
__('Please go back and try again.');
throw new SymphonyErrorPage($msg, __('Access Denied'), 'generic', array(), Page::HTTP_STATUS_FORBIDDEN);
}
/**
* Return's the location of the XSRF tokens in the Session
*
* @deprecated This function will be removed in Symphony 3.0. Use
* `getSessionToken()` instead.
* @return string|null
*/
public static function getSession()
{
if (Symphony::Log()) {
Symphony::Log()->pushDeprecateWarningToLog('XSRF::getSession()', 'XSRF::getSessionToken()');
}
return self::getSessionToken();
}
}