Project

General

Profile

Download (13.9 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2

    
3
/**
4
 * @file
5
 *
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).
12
 *
13
 * This library is PHP4 and PHP5 compatible.
14
 */
15

    
16
include_once('phpsessionmanager.inc');
17

    
18
// CONFIGURATION:
19

    
20
/**
21
 * By default, when you include this file csrf-magic will automatically check
22
 * and exit if the CSRF token is invalid. This will defer executing
23
 * csrf_check() until you're ready.  You can also pass false as a parameter to
24
 * that function, in which case the function will not exit but instead return
25
 * a boolean false if the CSRF check failed. This allows for tighter integration
26
 * with your system.
27
 */
28
$GLOBALS['csrf']['defer'] = false;
29

    
30
/**
31
 * This is the amount of seconds you wish to allow before any token becomes
32
 * invalid; the default is two hours, which should be more than enough for
33
 * most websites.
34
 */
35
$GLOBALS['csrf']['expires'] = 7200;
36

    
37
/**
38
 * Callback function to execute when there's the CSRF check fails and
39
 * $fatal == true (see csrf_check). This will usually output an error message
40
 * about the failure.
41
 */
42
$GLOBALS['csrf']['callback'] = 'csrf_callback';
43

    
44
/**
45
 * Whether or not to include our JavaScript library which also rewrites
46
 * AJAX requests on this domain. Set this to the web path. This setting only works
47
 * with supported JavaScript libraries in Internet Explorer; see README.txt for
48
 * a list of supported libraries.
49
 */
50
$GLOBALS['csrf']['rewrite-js'] = false;
51

    
52
/**
53
 * A secret key used when hashing items. Please generate a random string and
54
 * place it here. If you change this value, all previously generated tokens
55
 * will become invalid.
56
 */
57
$GLOBALS['csrf']['secret'] = '';
58
// nota bene: library code should use csrf_get_secret() and not access
59
// this global directly
60

    
61
/**
62
 * Set this to false to disable csrf-magic's output handler, and therefore,
63
 * its rewriting capabilities. If you're serving non HTML content, you should
64
 * definitely set this false.
65
 */
66
$GLOBALS['csrf']['rewrite'] = true;
67

    
68
/**
69
 * Whether or not to use IP addresses when binding a user to a token. This is
70
 * less reliable and less secure than sessions, but is useful when you need
71
 * to give facilities to anonymous users and do not wish to maintain a database
72
 * of valid keys.
73
 */
74
$GLOBALS['csrf']['allow-ip'] = true;
75

    
76
/**
77
 * If this information is available, use the cookie by this name to determine
78
 * whether or not to allow the request. This is a shortcut implementation
79
 * very similar to 'key', but we randomly set the cookie ourselves.
80
 */
81
$GLOBALS['csrf']['cookie'] = '__csrf_cookie';
82

    
83
/**
84
 * If this information is available, set this to a unique identifier (it
85
 * can be an integer or a unique username) for the current "user" of this
86
 * application. The token will then be globally valid for all of that user's
87
 * operations, but no one else. This requires that 'secret' be set.
88
 */
89
$GLOBALS['csrf']['user'] = false;
90

    
91
/**
92
 * This is an arbitrary secret value associated with the user's session. This
93
 * will most probably be the contents of a cookie, as an attacker cannot easily
94
 * determine this information. Warning: If the attacker knows this value, they
95
 * can easily spoof a token. This is a generic implementation; sessions should
96
 * work in most cases.
97
 *
98
 * Why would you want to use this? Lets suppose you have a squid cache for your
99
 * website, and the presence of a session cookie bypasses it. Let's also say
100
 * you allow anonymous users to interact with the website; submitting forms
101
 * and AJAX. Previously, you didn't have any CSRF protection for anonymous users
102
 * and so they never got sessions; you don't want to start using sessions either,
103
 * otherwise you'll bypass the Squid cache. Setup a different cookie for CSRF
104
 * tokens, and have Squid ignore that cookie for get requests, for anonymous
105
 * users. (If you haven't guessed, this scheme was(?) used for MediaWiki).
106
 */
107
$GLOBALS['csrf']['key'] = false;
108

    
109
/**
110
 * The name of the magic CSRF token that will be placed in all forms, i.e.
111
 * the contents of <input type="hidden" name="$name" value="CSRF-TOKEN" />
112
 */
113
$GLOBALS['csrf']['input-name'] = '__csrf_magic';
114

    
115
/**
116
 * Set this to false if your site must work inside of frame/iframe elements,
117
 * but do so at your own risk: this configuration protects you against CSS
118
 * overlay attacks that defeat tokens.
119
 */
120
$GLOBALS['csrf']['frame-breaker'] = true;
121

    
122
/**
123
 * Whether or not CSRF Magic should be allowed to start a new session in order
124
 * to determine the key.
125
 */
126
$GLOBALS['csrf']['auto-session'] = true;
127

    
128
/**
129
 * Whether or not csrf-magic should produce XHTML style tags.
130
 */
131
$GLOBALS['csrf']['xhtml'] = true;
132

    
133
// FUNCTIONS:
134

    
135
// Don't edit this!
136
$GLOBALS['csrf']['version'] = '1.0.4';
137

    
138
/**
139
 * Rewrites <form> on the fly to add CSRF tokens to them. This can also
140
 * inject our JavaScript library.
141
 */
142
function csrf_ob_handler($buffer, $flags) {
143
    // Even though the user told us to rewrite, we should do a quick heuristic
144
    // to check if the page is *actually* HTML. We don't begin rewriting until
145
    // we hit the first <html tag.
146
    static $is_html = false;
147
    if (!$is_html) {
148
        // not HTML until proven otherwise
149
        if (stripos($buffer, '<html') !== false) {
150
            $is_html = true;
151
        } else {
152
            return $buffer;
153
        }
154
    }
155
    $tokens = csrf_get_tokens();
156
    $name = $GLOBALS['csrf']['input-name'];
157
    $endslash = $GLOBALS['csrf']['xhtml'] ? ' /' : '';
158
    $input = "<input type='hidden' name='$name' value=\"$tokens\"$endslash>";
159
    $buffer = preg_replace('#(<form[^>]*method\s*=\s*["\']post["\'][^>]*>)#i', '$1' . $input, $buffer);
160
    if ($GLOBALS['csrf']['frame-breaker']) {
161
        $buffer = str_ireplace('</head>', '<script type="text/javascript">if (top != self) {top.location.href = self.location.href;}</script></head>', $buffer);
162
    }
163
    if ($js = $GLOBALS['csrf']['rewrite-js']) {
164
        $buffer = str_ireplace(
165
            '</head>',
166
            '<script type="text/javascript">'.
167
                'var csrfMagicToken = "'.$tokens.'";'.
168
                'var csrfMagicName = "'.$name.'";</script>'.
169
            '<script src="'.$js.'" type="text/javascript"></script></head>',
170
            $buffer
171
        );
172
        $script = '<script type="text/javascript">CsrfMagic.end();</script>';
173
        $buffer = str_ireplace('</body>', $script . '</body>', $buffer, $count);
174
        if (!$count) {
175
            $buffer .= $script;
176
        }
177
    }
178
    return $buffer;
179
}
180

    
181
/**
182
 * Checks if this is a post request, and if it is, checks if the nonce is valid.
183
 * @param bool $fatal Whether or not to fatally error out if there is a problem.
184
 * @return True if check passes or is not necessary, false if failure.
185
 */
186
function csrf_check($fatal = true) {
187
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') return true;
188
    csrf_start();
189
    $name = $GLOBALS['csrf']['input-name'];
190
    $ok = false;
191
    $tokens = '';
192
    do {
193
        if (!isset($_POST[$name])) break;
194
        // we don't regenerate a token and check it because some token creation
195
        // schemes are volatile.
196
        $tokens = $_POST[$name];
197
        if (!csrf_check_tokens($tokens)) break;
198
        $ok = true;
199
    } while (false);
200
    if ($fatal && !$ok) {
201
        $callback = $GLOBALS['csrf']['callback'];
202
        if (trim($tokens, 'A..Za..z0..9:;,') !== '') $tokens = 'hidden';
203
        $callback($tokens);
204
        phpsession_end();
205
        exit;
206
    }
207
    return $ok;
208
}
209

    
210
/**
211
 * Retrieves a valid token(s) for a particular context. Tokens are separated
212
 * by semicolons.
213
 */
214
function csrf_get_tokens() {
215
    $has_cookies = !empty($_COOKIE);
216

    
217
    // $ip implements a composite key, which is sent if the user hasn't sent
218
    // any cookies. It may or may not be used, depending on whether or not
219
    // the cookies "stick"
220
    $secret = csrf_get_secret();
221
    if (!$has_cookies && $secret) {
222
        // :TODO: Harden this against proxy-spoofing attacks
223
        $IP_ADDRESS = (isset($_SERVER['IP_ADDRESS']) ? $_SERVER['IP_ADDRESS'] : $_SERVER['REMOTE_ADDR']);
224
        $ip = ';ip:' . csrf_hash($IP_ADDRESS);
225
    } else {
226
        $ip = '';
227
    }
228
    csrf_start();
229

    
230
    // These are "strong" algorithms that don't require per se a secret
231
    if (session_id()) return 'sid:' . csrf_hash(session_id()) . $ip;
232
    if ($GLOBALS['csrf']['cookie']) {
233
        $val = csrf_generate_secret();
234
        setcookie($GLOBALS['csrf']['cookie'], $val);
235
        return 'cookie:' . csrf_hash($val) . $ip;
236
    }
237
    if ($GLOBALS['csrf']['key']) return 'key:' . csrf_hash($GLOBALS['csrf']['key']) . $ip;
238
    // These further algorithms require a server-side secret
239
    if (!$secret) return 'invalid';
240
    if ($GLOBALS['csrf']['user'] !== false) {
241
        return 'user:' . csrf_hash($GLOBALS['csrf']['user']);
242
    }
243
    if ($GLOBALS['csrf']['allow-ip']) {
244
        return ltrim($ip, ';');
245
    }
246
    return 'invalid';
247
}
248

    
249
function csrf_flattenpost($data) {
250
    $ret = array();
251
    foreach($data as $n => $v) {
252
        $ret = array_merge($ret, csrf_flattenpost2(1, $n, $v));
253
    }
254
    return $ret;
255
}
256
function csrf_flattenpost2($level, $key, $data) {
257
    if(!is_array($data)) return array($key => $data);
258
    $ret = array();
259
    foreach($data as $n => $v) {
260
        $nk = $level >= 1 ? $key."[$n]" : "[$n]";
261
        $ret = array_merge($ret, csrf_flattenpost2($level+1, $nk, $v));
262
    }
263
    return $ret;
264
}
265

    
266
/**
267
 * @param $tokens is safe for HTML consumption
268
 */
269
function csrf_callback($tokens) {
270
    // (yes, $tokens is safe to echo without escaping)
271
    header($_SERVER['SERVER_PROTOCOL'] . ' 403 Forbidden');
272
    $data = '';
273
    foreach (csrf_flattenpost($_POST) as $key => $value) {
274
        if ($key == $GLOBALS['csrf']['input-name']) continue;
275
        $data .= '<input type="hidden" name="'.htmlspecialchars($key).'" value="'.htmlspecialchars($value).'" />';
276
    }
277
    echo "<html><head><title>CSRF check failed</title></head>
278
        <body>
279
        <p>CSRF check failed. Your form session may have expired, or you may not have
280
        cookies enabled.</p>
281
        <form method='post' action=''>$data<input type='submit' value='Try again' /></form>
282
        <p>Debug: $tokens</p></body></html>
283
";
284
}
285

    
286
/**
287
 * Checks if a composite token is valid. Outward facing code should use this
288
 * instead of csrf_check_token()
289
 */
290
function csrf_check_tokens($tokens) {
291
    if (is_string($tokens)) $tokens = explode(';', $tokens);
292
    foreach ($tokens as $token) {
293
        if (csrf_check_token($token)) return true;
294
    }
295
    return false;
296
}
297

    
298
/**
299
 * Checks if a token is valid.
300
 */
301
function csrf_check_token($token) {
302
    if (strpos($token, ':') === false) return false;
303
    list($type, $value) = explode(':', $token, 2);
304
    if (strpos($value, ',') === false) return false;
305
    list($x, $time) = explode(',', $token, 2);
306
    if ($GLOBALS['csrf']['expires']) {
307
        if (time() > $time + $GLOBALS['csrf']['expires']) return false;
308
    }
309
    switch ($type) {
310
        case 'sid':
311
            return $value === csrf_hash(session_id(), $time);
312
        case 'cookie':
313
            $n = $GLOBALS['csrf']['cookie'];
314
            if (!$n) return false;
315
            if (!isset($_COOKIE[$n])) return false;
316
            return $value === csrf_hash($_COOKIE[$n], $time);
317
        case 'key':
318
            if (!$GLOBALS['csrf']['key']) return false;
319
            return $value === csrf_hash($GLOBALS['csrf']['key'], $time);
320
        // We could disable these 'weaker' checks if 'key' was set, but
321
        // that doesn't make me feel good then about the cookie-based
322
        // implementation.
323
        case 'user':
324
            if (!csrf_get_secret()) return false;
325
            if ($GLOBALS['csrf']['user'] === false) return false;
326
            return $value === csrf_hash($GLOBALS['csrf']['user'], $time);
327
        case 'ip':
328
            if (!csrf_get_secret()) return false;
329
            // do not allow IP-based checks if the username is set, or if
330
            // the browser sent cookies
331
            if ($GLOBALS['csrf']['user'] !== false) return false;
332
            if (!empty($_COOKIE)) return false;
333
            if (!$GLOBALS['csrf']['allow-ip']) return false;
334
            $IP_ADDRESS = (isset($_SERVER['IP_ADDRESS']) ? $_SERVER['IP_ADDRESS'] : $_SERVER['REMOTE_ADDR']);
335
            return $value === csrf_hash($IP_ADDRESS, $time);
336
    }
337
    return false;
338
}
339

    
340
/**
341
 * Sets a configuration value.
342
 */
343
function csrf_conf($key, $val) {
344
    if (!isset($GLOBALS['csrf'][$key])) {
345
        trigger_error('No such configuration ' . $key, E_USER_WARNING);
346
        return;
347
    }
348
    $GLOBALS['csrf'][$key] = $val;
349
}
350

    
351
/**
352
 * Starts a session if we're allowed to.
353
 */
354
function csrf_start() {
355
    if ($GLOBALS['csrf']['auto-session'] && !session_id()) {
356
        phpsession_begin();
357
    }
358
}
359

    
360
/**
361
 * Retrieves the secret, and generates one if necessary.
362
 */
363
function csrf_get_secret() {
364
    if ($GLOBALS['csrf']['secret']) return $GLOBALS['csrf']['secret'];
365
    $dir = dirname(__FILE__);
366
    $file = $dir . '/csrf-secret.php';
367
    $secret = '';
368
    if (file_exists($file)) {
369
        include $file;
370
        return $secret;
371
    }
372
    if (is_writable($dir)) {
373
        $secret = csrf_generate_secret();
374
        $fh = fopen($file, 'w');
375
        fwrite($fh, '<?php $secret = "'.$secret.'";' . PHP_EOL);
376
        fclose($fh);
377
        return $secret;
378
    }
379
    return '';
380
}
381

    
382
/**
383
 * Generates a random string as the hash of time, microtime, and mt_rand.
384
 */
385
function csrf_generate_secret($len = 32) {
386
    $r = '';
387
    for ($i = 0; $i < $len; $i++) {
388
        $r .= chr(mt_rand(0, 255));
389
    }
390
    $r .= time() . microtime();
391
    return sha1($r);
392
}
393

    
394
/**
395
 * Generates a hash/expiry double. If time isn't set it will be calculated
396
 * from the current time.
397
 */
398
function csrf_hash($value, $time = null) {
399
    if (!$time) $time = time();
400
    return sha1(csrf_get_secret() . $value . $time) . ',' . $time;
401
}
402

    
403
// Load user configuration
404
if (function_exists('csrf_startup')) csrf_startup();
405
// Initialize our handler
406
if ($GLOBALS['csrf']['rewrite'])     ob_start('csrf_ob_handler');
407
// Perform check
408
if (!$GLOBALS['csrf']['defer'])      csrf_check();
(2-2/2)