Add native support for 'cookie' tokens. Also, more informative error messages.
[csrf-magic.git] / csrf-magic.php
blob8142806dd994e2a7ef1c9bd3a700a3b9dd66bab4
1 <?php
3 /**
4 * @file
6 * csrf-magic is a PHP library that makes adding CSRF-protection to your
7 * web applications a snap. No need to modify every form or create a database
8 * of valid nonces; just include this file at the top of every
9 * web-accessible page (or even better, your common include file included
10 * in every page), and forget about it! (There are, of course, configuration
11 * options for advanced users).
13 * This library is PHP4 and PHP5 compatible.
16 // CONFIGURATION:
18 /**
19 * By default, when you include this file csrf-magic will automatically check
20 * and exit if the CSRF token is invalid. This will defer executing
21 * csrf_check() until you're ready. You can also pass false as a parameter to
22 * that function, in which case the function will not exit but instead return
23 * a boolean false if the CSRF check failed. This allows for tighter integration
24 * with your system.
26 $GLOBALS['csrf']['defer'] = false;
28 /**
29 * Callback function to execute when there's the CSRF check fails and
30 * $fatal == true (see csrf_check). This will usually output an error message
31 * about the failure.
33 $GLOBALS['csrf']['callback'] = 'csrf_callback';
35 /**
36 * Whether or not to include our JavaScript library which also rewrites
37 * AJAX requests on this domain. Set this to the web path. This setting only works
38 * with supported JavaScript libraries in Internet Explorer; see README.txt for
39 * a list of supported libraries.
41 $GLOBALS['csrf']['rewrite-js'] = false;
43 /**
44 * A secret key used when hashing items. Please generate a random string and
45 * place it here. If you change this value, all previously generated tokens
46 * will become invalid.
48 $GLOBALS['csrf']['secret'] = '';
50 /**
51 * Set this to false to disable csrf-magic's output handler, and therefore,
52 * its rewriting capabilities. If you're serving non HTML content, you should
53 * definitely set this false.
55 $GLOBALS['csrf']['rewrite'] = true;
57 /**
58 * Whether or not to use IP addresses when binding a user to a token. This is
59 * less reliable and less secure than sessions, but is useful when you need
60 * to give facilities to anonymous users and do not wish to maintain a database
61 * of valid keys.
63 $GLOBALS['csrf']['allow-ip'] = true;
65 /**
66 * If this information is available, use the cookie by this name to determine
67 * whether or not to allow the request. This is a shortcut implementation
68 * very similar to 'key', but we randomly set the cookie ourselves.
70 $GLOBALS['csrf']['cookie'] = '__csrf_cookie';
72 /**
73 * If this information is available, set this to a unique identifier (it
74 * can be an integer or a unique username) for the current "user" of this
75 * application. The token will then be globally valid for all of that user's
76 * operations, but no one else. This requires that 'secret' be set.
78 $GLOBALS['csrf']['user'] = false;
80 /**
81 * This is an arbitrary secret value associated with the user's session. This
82 * will most probably be the contents of a cookie, as an attacker cannot easily
83 * determine this information. Warning: If the attacker knows this value, they
84 * can easily spoof a token. This is a generic implementation; sessions should
85 * work in most cases.
87 * Why would you want to use this? Lets suppose you have a squid cache for your
88 * website, and the presence of a session cookie bypasses it. Let's also say
89 * you allow anonymous users to interact with the website; submitting forms
90 * and AJAX. Previously, you didn't have any CSRF protection for anonymous users
91 * and so they never got sessions; you don't want to start using sessions either,
92 * otherwise you'll bypass the Squid cache. Setup a different cookie for CSRF
93 * tokens, and have Squid ignore that cookie for get requests, for anonymous
94 * users. (If you haven't guessed, this scheme was(?) used for MediaWiki).
96 $GLOBALS['csrf']['key'] = false;
98 /**
99 * The name of the magic CSRF token that will be placed in all forms, i.e.
100 * the contents of <input type="hidden" name="$name" value="CSRF-TOKEN" />
102 $GLOBALS['csrf']['input-name'] = '__csrf_magic';
105 * Whether or not CSRF Magic should be allowed to start a new session in order
106 * to determine the key.
108 $GLOBALS['csrf']['auto-session'] = true;
111 * Whether or not csrf-magic should produce XHTML style tags.
113 $GLOBALS['csrf']['xhtml'] = true;
115 // FUNCTIONS:
117 // Don't edit this!
118 $GLOBALS['csrf']['version'] = '1.0.0';
121 * Rewrites <form> on the fly to add CSRF tokens to them. This can also
122 * inject our JavaScript library.
124 function csrf_ob_handler($buffer, $flags) {
125 // Even though the user told us to rewrite, we should do a quick heuristic
126 // to check if the page is *actually* HTML. We don't begin rewriting until
127 // we hit the first <html tag.
128 static $is_html = false;
129 if (!$is_html) {
130 // not HTML until proven otherwise
131 if (stripos($buffer, '<html') !== false) {
132 $is_html = true;
133 } else {
134 return $buffer;
137 $tokens = csrf_get_tokens();
138 $name = $GLOBALS['csrf']['input-name'];
139 $endslash = $GLOBALS['csrf']['xhtml'] ? ' /' : '';
140 $input = "<input type='hidden' name='$name' value=\"$tokens\"$endslash>";
141 $buffer = preg_replace('#(<form[^>]*method\s*=\s*["\']post["\'][^>]*>)#i', '$1' . $input, $buffer);
142 if ($js = $GLOBALS['csrf']['rewrite-js']) {
143 $buffer = preg_replace(
144 '#(</head>)#i',
145 '<script type="text/javascript">'.
146 'var csrfMagicToken = "'.$tokens.'";'.
147 'var csrfMagicName = "'.$name.'";</script>'.
148 '<script src="'.$js.'" type="text/javascript"></script>$1',
149 $buffer
151 $script = '<script type="text/javascript">CsrfMagic.end();</script>';
152 $buffer = str_ireplace('</body>', $script . '</body>', $buffer, $count);
153 if (!$count) {
154 $buffer .= $script;
157 return $buffer;
161 * Checks if this is a post request, and if it is, checks if the nonce is valid.
162 * @param bool $fatal Whether or not to fatally error out if there is a problem.
163 * @return True if check passes or is not necessary, false if failure.
165 function csrf_check($fatal = true) {
166 if ($_SERVER['REQUEST_METHOD'] !== 'POST') return true;
167 csrf_start();
168 $name = $GLOBALS['csrf']['input-name'];
169 $ok = false;
170 $tokens = '';
171 do {
172 if (!isset($_POST[$name])) break;
173 // we don't regenerate a token and check it because some token creation
174 // schemes are volatile.
175 $tokens = $_POST[$name];
176 if (!csrf_check_tokens($tokens)) break;
177 $ok = true;
178 } while (false);
179 if ($fatal && !$ok) {
180 $callback = $GLOBALS['csrf']['callback'];
181 if (trim($tokens, 'A..Za..z0..9:;') !== '') $tokens = 'hidden';
182 $callback($tokens);
183 exit;
185 return $ok;
189 * Retrieves a valid token(s) for a particular context. Tokens are separated
190 * by semicolons.
192 function csrf_get_tokens() {
193 $secret = csrf_get_secret();
194 $has_cookies = !empty($_COOKIE);
196 // $ip implements a composite key, which is sent if the user hasn't sent
197 // any cookies. It may or may not be used, depending on whether or not
198 // the cookies "stick"
199 if (!$has_cookies && $secret) {
200 // :TODO: Harden this against proxy-spoofing attacks
201 $ip = ';ip:' . sha1($secret . $_SERVER['IP_ADDRESS']);
202 } else {
203 $ip = '';
205 csrf_start();
207 // These are "strong" algorithms that don't require per se a secret
208 if (session_id()) return 'sid:' . sha1($secret . session_id()) . $ip;
209 if ($GLOBALS['csrf']['cookie']) {
210 $val = csrf_generate_secret();
211 setcookie($GLOBALS['csrf']['cookie'], $val);
212 return 'cookie:' . sha1($secret . $val) . $ip;
214 if ($GLOBALS['csrf']['key']) return 'key:' . sha1($secret . $GLOBALS['csrf']['key']) . $ip;
215 // These further algorithms require a server-side secret
216 if ($secret === '') return 'invalid';
217 if ($GLOBALS['csrf']['user'] !== false) {
218 return 'user:' . sha1($secret . $GLOBALS['csrf']['user']);
220 if ($GLOBALS['csrf']['allow-ip']) {
221 return ltrim($ip, ';');
223 return 'invalid';
227 * @param $tokens is safe for HTML consumption
229 function csrf_callback($tokens) {
230 header($_SERVER['SERVER_PROTOCOL'] . ' 403 Forbidden');
231 echo "<html><head><title>CSRF check failed</title></head><body>CSRF check failed. Please enable cookies.<br />Debug: ".$tokens."</body></html>
236 * Checks if a composite token is valid. Outward facing code should use this
237 * instead of csrf_check_token()
239 function csrf_check_tokens($tokens) {
240 if (is_string($tokens)) $tokens = explode(';', $tokens);
241 foreach ($tokens as $token) {
242 if (csrf_check_token($token)) return true;
244 return false;
248 * Checks if a token is valid.
250 function csrf_check_token($token) {
251 if (strpos($token, ':') === false) return false;
252 list($type, $value) = explode(':', $token, 2);
253 $secret = csrf_get_secret();
254 switch ($type) {
255 case 'sid':
256 return $value === sha1($secret . session_id());
257 case 'cookie':
258 $n = $GLOBALS['csrf']['cookie'];
259 if (!$n) return false;
260 if (!isset($_COOKIE[$n])) return false;
261 return $value === sha1($secret . $_COOKIE[$n]);
262 case 'key':
263 if (!$GLOBALS['csrf']['key']) return false;
264 return $value === sha1($secret . $GLOBALS['csrf']['key']);
265 // We could disable these 'weaker' checks if 'key' was set, but
266 // that doesn't make me feel good then about the cookie-based
267 // implementation.
268 case 'user':
269 if ($GLOBALS['csrf']['secret'] === '') return false;
270 if ($GLOBALS['csrf']['user'] === false) return false;
271 return $value === sha1($secret . $GLOBALS['csrf']['user']);
272 case 'ip':
273 if (csrf_get_secret() === '') return false;
274 // do not allow IP-based checks if the username is set, or if
275 // the browser sent cookies
276 if ($GLOBALS['csrf']['user'] !== false) return false;
277 if (!empty($_COOKIE)) return false;
278 if (!$GLOBALS['csrf']['allow-ip']) return false;
279 return $value === sha1($secret . $_SERVER['IP_ADDRESS']);
281 return false;
285 * Sets a configuration value.
287 function csrf_conf($key, $val) {
288 if (!isset($GLOBALS['csrf'][$key])) {
289 trigger_error('No such configuration ' . $key, E_USER_WARNING);
290 return;
292 $GLOBALS['csrf'][$key] = $val;
296 * Starts a session if we're allowed to.
298 function csrf_start() {
299 if ($GLOBALS['csrf']['auto-session'] && !session_id()) {
300 session_start();
305 * Retrieves the secret, and generates one if necessary.
307 function csrf_get_secret() {
308 if ($GLOBALS['csrf']['secret']) return $GLOBALS['csrf']['secret'];
309 $dir = dirname(__FILE__);
310 $file = $dir . '/csrf-secret.php';
311 $secret = '';
312 if (file_exists($file)) {
313 include $file;
314 return $secret;
316 if (is_writable($dir)) {
317 $secret = csrf_generate_secret();
318 $fh = fopen($file, 'w');
319 fwrite($fh, '<?php $secret = "'.$secret.'";' . PHP_EOL);
320 fclose($fh);
321 return $secret;
323 return '';
327 * Generates a random string as the hash of time, microtime, and mt_rand.
329 function csrf_generate_secret($len = 32) {
330 $secret = '';
331 for ($i = 0; $i < 32; $i++) {
332 $secret .= chr(mt_rand(0, 255));
334 $secret .= time() . microtime();
335 return sha1($secret);
338 // Load user configuration
339 if (function_exists('csrf_startup')) csrf_startup();
340 // Initialize our handler
341 if ($GLOBALS['csrf']['rewrite']) ob_start('csrf_ob_handler');
342 // Perform check
343 if (!$GLOBALS['csrf']['defer']) csrf_check();