blob: 510f3d1ae85cdcff82c83a4a8faf76d0b5f11362 [file] [log] [blame]
Derek Jones37f4b9c2011-07-01 17:56:50 -05001<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
Derek Jonese701d762010-03-02 18:17:01 -06002/**
3 * CodeIgniter
4 *
Greg Aker741de1c2010-11-10 14:52:57 -06005 * An open source application development framework for PHP 5.1.6 or newer
Derek Jonese701d762010-03-02 18:17:01 -06006 *
Derek Jonesf4a4bd82011-10-20 12:18:42 -05007 * NOTICE OF LICENSE
8 *
9 * Licensed under the Open Software License version 3.0
10 *
11 * This source file is subject to the Open Software License (OSL 3.0) that is
12 * bundled with this package in the files license.txt / license.rst. It is
13 * also available through the world wide web at this URL:
14 * http://opensource.org/licenses/OSL-3.0
15 * If you did not receive a copy of the license and are unable to obtain it
16 * through the world wide web, please send an email to
17 * licensing@ellislab.com so we can send you a copy immediately.
18 *
Derek Jonese701d762010-03-02 18:17:01 -060019 * @package CodeIgniter
Derek Jonesf4a4bd82011-10-20 12:18:42 -050020 * @author EllisLab Dev Team
21 * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. (http://ellislab.com/)
22 * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
Derek Jonese701d762010-03-02 18:17:01 -060023 * @link http://codeigniter.com
24 * @since Version 1.0
25 * @filesource
26 */
27
28// ------------------------------------------------------------------------
29
30/**
31 * Security Class
32 *
33 * @package CodeIgniter
34 * @subpackage Libraries
35 * @category Security
Derek Jonesf4a4bd82011-10-20 12:18:42 -050036 * @author EllisLab Dev Team
Pascal Krietec9c045a2011-04-05 14:50:41 -040037 * @link http://codeigniter.com/user_guide/libraries/security.html
Derek Jonese701d762010-03-02 18:17:01 -060038 */
39class CI_Security {
Barry Mienydd671972010-10-04 16:33:58 +020040
David Behler07b53422011-08-15 00:25:06 +020041 /**
42 * Random Hash for protecting URLs
43 *
44 * @var string
45 * @access protected
46 */
47 protected $_xss_hash = '';
Andrey Andreev3d113bd2011-10-05 00:03:20 +030048
David Behler07b53422011-08-15 00:25:06 +020049 /**
50 * Random Hash for Cross Site Request Forgery Protection Cookie
51 *
52 * @var string
53 * @access protected
54 */
55 protected $_csrf_hash = '';
Andrey Andreev3d113bd2011-10-05 00:03:20 +030056
David Behler07b53422011-08-15 00:25:06 +020057 /**
58 * Expiration time for Cross Site Request Forgery Protection Cookie
59 * Defaults to two hours (in seconds)
60 *
61 * @var int
62 * @access protected
63 */
64 protected $_csrf_expire = 7200;
Andrey Andreev3d113bd2011-10-05 00:03:20 +030065
David Behler07b53422011-08-15 00:25:06 +020066 /**
67 * Token name for Cross Site Request Forgery Protection Cookie
68 *
69 * @var string
70 * @access protected
71 */
72 protected $_csrf_token_name = 'ci_csrf_token';
Andrey Andreev3d113bd2011-10-05 00:03:20 +030073
David Behler07b53422011-08-15 00:25:06 +020074 /**
75 * Cookie name for Cross Site Request Forgery Protection Cookie
76 *
77 * @var string
78 * @access protected
79 */
80 protected $_csrf_cookie_name = 'ci_csrf_token';
Andrey Andreev3d113bd2011-10-05 00:03:20 +030081
David Behler07b53422011-08-15 00:25:06 +020082 /**
83 * List of never allowed strings
84 *
85 * @var array
86 * @access protected
87 */
Andrey Andreev3d113bd2011-10-05 00:03:20 +030088
Pascal Krietec9c045a2011-04-05 14:50:41 -040089 protected $_never_allowed_str = array(
90 'document.cookie' => '[removed]',
91 'document.write' => '[removed]',
92 '.parentNode' => '[removed]',
93 '.innerHTML' => '[removed]',
94 'window.location' => '[removed]',
95 '-moz-binding' => '[removed]',
96 '<!--' => '&lt;!--',
97 '-->' => '--&gt;',
Pascal Krietec38e3b62011-11-14 13:55:00 -050098 '<![CDATA[' => '&lt;![CDATA[',
99 '<comment>' => '&lt;comment&gt;'
Pascal Krietec9c045a2011-04-05 14:50:41 -0400100 );
Derek Jonese701d762010-03-02 18:17:01 -0600101
David Behler07b53422011-08-15 00:25:06 +0200102 /**
103 * List of never allowed regex replacement
104 *
105 * @var array
106 * @access protected
107 */
Pascal Krietec9c045a2011-04-05 14:50:41 -0400108 protected $_never_allowed_regex = array(
109 "javascript\s*:" => '[removed]',
110 "expression\s*(\(|&\#40;)" => '[removed]', // CSS and IE
111 "vbscript\s*:" => '[removed]', // IE, surprise!
112 "Redirect\s+302" => '[removed]'
113 );
David Behler07b53422011-08-15 00:25:06 +0200114
Pascal Krietec9c045a2011-04-05 14:50:41 -0400115 /**
116 * Constructor
117 */
Greg Akera9263282010-11-10 15:26:43 -0600118 public function __construct()
Derek Jonese701d762010-03-02 18:17:01 -0600119 {
patworkef1a55a2011-04-09 13:04:06 +0200120 // CSRF config
121 foreach(array('csrf_expire', 'csrf_token_name', 'csrf_cookie_name') as $key)
122 {
123 if (FALSE !== ($val = config_item($key)))
124 {
125 $this->{'_'.$key} = $val;
126 }
127 }
128
patwork9e267982011-04-11 13:02:32 +0200129 // Append application specific cookie prefix
Greg Akerb3e614d2011-04-19 20:19:17 -0500130 if (config_item('cookie_prefix'))
131 {
patwork9e267982011-04-11 13:02:32 +0200132 $this->_csrf_cookie_name = config_item('cookie_prefix').$this->_csrf_cookie_name;
133 }
Derek Jonesb3f10a22010-07-25 19:11:26 -0500134
Derek Jonese701d762010-03-02 18:17:01 -0600135 // Set the CSRF hash
136 $this->_csrf_set_hash();
Derek Allard958543a2010-07-22 14:10:26 -0400137
Derek Jonese701d762010-03-02 18:17:01 -0600138 log_message('debug', "Security Class Initialized");
139 }
140
141 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200142
Derek Jonese701d762010-03-02 18:17:01 -0600143 /**
144 * Verify Cross Site Request Forgery Protection
145 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400146 * @return object
Derek Jonese701d762010-03-02 18:17:01 -0600147 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500148 public function csrf_verify()
Derek Allard958543a2010-07-22 14:10:26 -0400149 {
Derek Jonese701d762010-03-02 18:17:01 -0600150 // If no POST data exists we will set the CSRF cookie
151 if (count($_POST) == 0)
152 {
153 return $this->csrf_set_cookie();
154 }
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300155
Alex Bilbieaeb2c3e2011-08-21 16:14:54 +0100156 // Check if URI has been whitelisted from CSRF checks
157 if ($exclude_uris = config_item('csrf_exclude_uris'))
158 {
159 $uri = load_class('URI', 'core');
160 if (in_array($uri->uri_string(), $exclude_uris))
161 {
162 return $this;
163 }
164 }
Derek Jonese701d762010-03-02 18:17:01 -0600165
166 // Do the tokens exist in both the _POST and _COOKIE arrays?
David Behler07b53422011-08-15 00:25:06 +0200167 if ( ! isset($_POST[$this->_csrf_token_name]) OR
Pascal Krietec9c045a2011-04-05 14:50:41 -0400168 ! isset($_COOKIE[$this->_csrf_cookie_name]))
Derek Jonese701d762010-03-02 18:17:01 -0600169 {
170 $this->csrf_show_error();
171 }
172
173 // Do the tokens match?
Pascal Krietec9c045a2011-04-05 14:50:41 -0400174 if ($_POST[$this->_csrf_token_name] != $_COOKIE[$this->_csrf_cookie_name])
Derek Jonese701d762010-03-02 18:17:01 -0600175 {
176 $this->csrf_show_error();
177 }
178
David Behler07b53422011-08-15 00:25:06 +0200179 // We kill this since we're done and we don't want to
Pascal Krietec9c045a2011-04-05 14:50:41 -0400180 // polute the _POST array
181 unset($_POST[$this->_csrf_token_name]);
Barry Mienydd671972010-10-04 16:33:58 +0200182
RS712be25a62011-12-31 16:02:04 -0200183 // Regenerate on every submission?
184 if (config_item('csrf_regenerate'))
185 {
186 // Nothing should last forever
187 unset($_COOKIE[$this->_csrf_cookie_name]);
188 $this->_csrf_hash = '';
189 }
190
Derek Jonesb3f10a22010-07-25 19:11:26 -0500191 $this->_csrf_set_hash();
192 $this->csrf_set_cookie();
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300193
Alex Bilbieaeb2c3e2011-08-21 16:14:54 +0100194 log_message('debug', "CSRF token verified");
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300195
Pascal Krietec9c045a2011-04-05 14:50:41 -0400196 return $this;
Derek Jonese701d762010-03-02 18:17:01 -0600197 }
Barry Mienydd671972010-10-04 16:33:58 +0200198
Derek Jonese701d762010-03-02 18:17:01 -0600199 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200200
Derek Jonese701d762010-03-02 18:17:01 -0600201 /**
202 * Set Cross Site Request Forgery Protection Cookie
203 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400204 * @return object
Derek Jonese701d762010-03-02 18:17:01 -0600205 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500206 public function csrf_set_cookie()
Derek Jonese701d762010-03-02 18:17:01 -0600207 {
Pascal Krietec9c045a2011-04-05 14:50:41 -0400208 $expire = time() + $this->_csrf_expire;
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300209 $secure_cookie = (bool) config_item('cookie_secure');
Derek Jonese701d762010-03-02 18:17:01 -0600210
Pascal Krietec9c045a2011-04-05 14:50:41 -0400211 if ($secure_cookie)
Derek Jonese701d762010-03-02 18:17:01 -0600212 {
Pascal Krietec9c045a2011-04-05 14:50:41 -0400213 $req = isset($_SERVER['HTTPS']) ? $_SERVER['HTTPS'] : FALSE;
214
215 if ( ! $req OR $req == 'off')
Derek Jonese701d762010-03-02 18:17:01 -0600216 {
Pascal Krietec9c045a2011-04-05 14:50:41 -0400217 return FALSE;
Derek Jonese701d762010-03-02 18:17:01 -0600218 }
219 }
Derek Allard958543a2010-07-22 14:10:26 -0400220
Pascal Krietec9c045a2011-04-05 14:50:41 -0400221 setcookie($this->_csrf_cookie_name, $this->_csrf_hash, $expire, config_item('cookie_path'), config_item('cookie_domain'), $secure_cookie);
222
223 log_message('debug', "CRSF cookie Set");
David Behler07b53422011-08-15 00:25:06 +0200224
Pascal Krietec9c045a2011-04-05 14:50:41 -0400225 return $this;
Derek Jonese701d762010-03-02 18:17:01 -0600226 }
227
228 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200229
Derek Jonese701d762010-03-02 18:17:01 -0600230 /**
231 * Show CSRF Error
232 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400233 * @return void
Derek Jonese701d762010-03-02 18:17:01 -0600234 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500235 public function csrf_show_error()
Derek Jonese701d762010-03-02 18:17:01 -0600236 {
237 show_error('The action you have requested is not allowed.');
238 }
239
240 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200241
Derek Jonese701d762010-03-02 18:17:01 -0600242 /**
David Behler07b53422011-08-15 00:25:06 +0200243 * Get CSRF Hash
Pascal Krietec9c045a2011-04-05 14:50:41 -0400244 *
David Behler07b53422011-08-15 00:25:06 +0200245 * Getter Method
Pascal Krietec9c045a2011-04-05 14:50:41 -0400246 *
247 * @return string self::_csrf_hash
248 */
249 public function get_csrf_hash()
250 {
251 return $this->_csrf_hash;
252 }
253
254 // --------------------------------------------------------------------
255
256 /**
257 * Get CSRF Token Name
258 *
259 * Getter Method
260 *
261 * @return string self::csrf_token_name
262 */
263 public function get_csrf_token_name()
264 {
265 return $this->_csrf_token_name;
266 }
267
268 // --------------------------------------------------------------------
269
270 /**
Derek Jonese701d762010-03-02 18:17:01 -0600271 * XSS Clean
272 *
273 * Sanitizes data so that Cross Site Scripting Hacks can be
Derek Jones37f4b9c2011-07-01 17:56:50 -0500274 * prevented. This function does a fair amount of work but
Derek Jonese701d762010-03-02 18:17:01 -0600275 * it is extremely thorough, designed to prevent even the
Derek Jones37f4b9c2011-07-01 17:56:50 -0500276 * most obscure XSS attempts. Nothing is ever 100% foolproof,
Derek Jonese701d762010-03-02 18:17:01 -0600277 * of course, but I haven't been able to get anything passed
278 * the filter.
279 *
280 * Note: This function should only be used to deal with data
Derek Jones37f4b9c2011-07-01 17:56:50 -0500281 * upon submission. It's not something that should
Derek Jonese701d762010-03-02 18:17:01 -0600282 * be used for general runtime processing.
283 *
284 * This function was based in part on some code and ideas I
285 * got from Bitflux: http://channel.bitflux.ch/wiki/XSS_Prevention
286 *
287 * To help develop this script I used this great list of
288 * vulnerabilities along with a few other hacks I've
289 * harvested from examining vulnerabilities in other programs:
290 * http://ha.ckers.org/xss.html
291 *
Derek Jonese701d762010-03-02 18:17:01 -0600292 * @param mixed string or array
David Behler07b53422011-08-15 00:25:06 +0200293 * @param bool
Derek Jonese701d762010-03-02 18:17:01 -0600294 * @return string
295 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500296 public function xss_clean($str, $is_image = FALSE)
Derek Jonese701d762010-03-02 18:17:01 -0600297 {
298 /*
299 * Is the string an array?
300 *
301 */
302 if (is_array($str))
303 {
304 while (list($key) = each($str))
305 {
306 $str[$key] = $this->xss_clean($str[$key]);
307 }
Barry Mienydd671972010-10-04 16:33:58 +0200308
Derek Jonese701d762010-03-02 18:17:01 -0600309 return $str;
310 }
311
312 /*
313 * Remove Invisible Characters
314 */
Greg Aker757dda62010-04-14 19:06:19 -0500315 $str = remove_invisible_characters($str);
Derek Jonese701d762010-03-02 18:17:01 -0600316
Pascal Krietec9c045a2011-04-05 14:50:41 -0400317 // Validate Entities in URLs
318 $str = $this->_validate_entities($str);
Derek Jonese701d762010-03-02 18:17:01 -0600319
320 /*
321 * URL Decode
322 *
323 * Just in case stuff like this is submitted:
324 *
325 * <a href="http://%77%77%77%2E%67%6F%6F%67%6C%65%2E%63%6F%6D">Google</a>
326 *
327 * Note: Use rawurldecode() so it does not remove plus signs
328 *
329 */
330 $str = rawurldecode($str);
Barry Mienydd671972010-10-04 16:33:58 +0200331
Derek Jonese701d762010-03-02 18:17:01 -0600332 /*
Barry Mienydd671972010-10-04 16:33:58 +0200333 * Convert character entities to ASCII
Derek Jonese701d762010-03-02 18:17:01 -0600334 *
335 * This permits our tests below to work reliably.
336 * We only convert entities that are within tags since
337 * these are the ones that will pose security problems.
338 *
339 */
340
341 $str = preg_replace_callback("/[a-z]+=([\'\"]).*?\\1/si", array($this, '_convert_attribute'), $str);
David Behler07b53422011-08-15 00:25:06 +0200342
Derek Jonese701d762010-03-02 18:17:01 -0600343 $str = preg_replace_callback("/<\w+.*?(?=>|<|$)/si", array($this, '_decode_entity'), $str);
344
345 /*
346 * Remove Invisible Characters Again!
347 */
Greg Aker757dda62010-04-14 19:06:19 -0500348 $str = remove_invisible_characters($str);
Barry Mienydd671972010-10-04 16:33:58 +0200349
Derek Jonese701d762010-03-02 18:17:01 -0600350 /*
351 * Convert all tabs to spaces
352 *
353 * This prevents strings like this: ja vascript
354 * NOTE: we deal with spaces between characters later.
David Behler07b53422011-08-15 00:25:06 +0200355 * NOTE: preg_replace was found to be amazingly slow here on
Pascal Krietec9c045a2011-04-05 14:50:41 -0400356 * large blocks of data, so we use str_replace.
Derek Jonese701d762010-03-02 18:17:01 -0600357 */
Barry Mienydd671972010-10-04 16:33:58 +0200358
Derek Jonese701d762010-03-02 18:17:01 -0600359 if (strpos($str, "\t") !== FALSE)
360 {
361 $str = str_replace("\t", ' ', $str);
362 }
Barry Mienydd671972010-10-04 16:33:58 +0200363
Derek Jonese701d762010-03-02 18:17:01 -0600364 /*
365 * Capture converted string for later comparison
366 */
367 $converted_string = $str;
Barry Mienydd671972010-10-04 16:33:58 +0200368
Pascal Krietec9c045a2011-04-05 14:50:41 -0400369 // Remove Strings that are never allowed
370 $str = $this->_do_never_allowed($str);
Derek Jonese701d762010-03-02 18:17:01 -0600371
372 /*
373 * Makes PHP tags safe
374 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400375 * Note: XML tags are inadvertently replaced too:
Derek Jonese701d762010-03-02 18:17:01 -0600376 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400377 * <?xml
Derek Jonese701d762010-03-02 18:17:01 -0600378 *
379 * But it doesn't seem to pose a problem.
Derek Jonese701d762010-03-02 18:17:01 -0600380 */
381 if ($is_image === TRUE)
382 {
David Behler07b53422011-08-15 00:25:06 +0200383 // Images have a tendency to have the PHP short opening and
384 // closing tags every so often so we skip those and only
Pascal Krietec9c045a2011-04-05 14:50:41 -0400385 // do the long opening tags.
Derek Jonese701d762010-03-02 18:17:01 -0600386 $str = preg_replace('/<\?(php)/i', "&lt;?\\1", $str);
387 }
388 else
389 {
Derek Jones37f4b9c2011-07-01 17:56:50 -0500390 $str = str_replace(array('<?', '?'.'>'), array('&lt;?', '?&gt;'), $str);
Derek Jonese701d762010-03-02 18:17:01 -0600391 }
Barry Mienydd671972010-10-04 16:33:58 +0200392
Derek Jonese701d762010-03-02 18:17:01 -0600393 /*
394 * Compact any exploded words
395 *
Derek Jones37f4b9c2011-07-01 17:56:50 -0500396 * This corrects words like: j a v a s c r i p t
Derek Jonese701d762010-03-02 18:17:01 -0600397 * These words are compacted back to their correct state.
Derek Jonese701d762010-03-02 18:17:01 -0600398 */
Pascal Krietec9c045a2011-04-05 14:50:41 -0400399 $words = array(
David Behler07b53422011-08-15 00:25:06 +0200400 'javascript', 'expression', 'vbscript', 'script',
Pascal Krietec9c045a2011-04-05 14:50:41 -0400401 'applet', 'alert', 'document', 'write', 'cookie', 'window'
402 );
David Behler07b53422011-08-15 00:25:06 +0200403
Derek Jonese701d762010-03-02 18:17:01 -0600404 foreach ($words as $word)
405 {
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300406 $word = implode("\s*", str_split($word)) . "\s*";
Derek Jonese701d762010-03-02 18:17:01 -0600407
408 // We only want to do this when it is followed by a non-word character
409 // That way valid stuff like "dealer to" does not become "dealerto"
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300410 $str = preg_replace_callback('#('.substr($word, 0, -3).')(\W)#is', array($this, '_compact_exploded_words'), $str);
Derek Jonese701d762010-03-02 18:17:01 -0600411 }
Barry Mienydd671972010-10-04 16:33:58 +0200412
Derek Jonese701d762010-03-02 18:17:01 -0600413 /*
414 * Remove disallowed Javascript in links or img tags
David Behler07b53422011-08-15 00:25:06 +0200415 * We used to do some version comparisons and use of stripos for PHP5,
416 * but it is dog slow compared to these simplified non-capturing
Pascal Krietec9c045a2011-04-05 14:50:41 -0400417 * preg_match(), especially if the pattern exists in the string
Derek Jonese701d762010-03-02 18:17:01 -0600418 */
419 do
420 {
421 $original = $str;
Barry Mienydd671972010-10-04 16:33:58 +0200422
Derek Jonese701d762010-03-02 18:17:01 -0600423 if (preg_match("/<a/i", $str))
424 {
425 $str = preg_replace_callback("#<a\s+([^>]*?)(>|$)#si", array($this, '_js_link_removal'), $str);
426 }
Barry Mienydd671972010-10-04 16:33:58 +0200427
Derek Jonese701d762010-03-02 18:17:01 -0600428 if (preg_match("/<img/i", $str))
429 {
430 $str = preg_replace_callback("#<img\s+([^>]*?)(\s?/?>|$)#si", array($this, '_js_img_removal'), $str);
431 }
Barry Mienydd671972010-10-04 16:33:58 +0200432
Derek Jonese701d762010-03-02 18:17:01 -0600433 if (preg_match("/script/i", $str) OR preg_match("/xss/i", $str))
434 {
435 $str = preg_replace("#<(/*)(script|xss)(.*?)\>#si", '[removed]', $str);
436 }
437 }
Pascal Krietec9c045a2011-04-05 14:50:41 -0400438 while($original != $str);
Derek Jonese701d762010-03-02 18:17:01 -0600439
440 unset($original);
441
Pascal Krietec9c045a2011-04-05 14:50:41 -0400442 // Remove evil attributes such as style, onclick and xmlns
443 $str = $this->_remove_evil_attributes($str, $is_image);
Barry Mienydd671972010-10-04 16:33:58 +0200444
Derek Jonese701d762010-03-02 18:17:01 -0600445 /*
446 * Sanitize naughty HTML elements
447 *
448 * If a tag containing any of the words in the list
449 * below is found, the tag gets converted to entities.
450 *
451 * So this: <blink>
452 * Becomes: &lt;blink&gt;
Derek Jonese701d762010-03-02 18:17:01 -0600453 */
454 $naughty = 'alert|applet|audio|basefont|base|behavior|bgsound|blink|body|embed|expression|form|frameset|frame|head|html|ilayer|iframe|input|isindex|layer|link|meta|object|plaintext|style|script|textarea|title|video|xml|xss';
455 $str = preg_replace_callback('#<(/*\s*)('.$naughty.')([^><]*)([><]*)#is', array($this, '_sanitize_naughty_html'), $str);
456
457 /*
458 * Sanitize naughty scripting elements
459 *
460 * Similar to above, only instead of looking for
461 * tags it looks for PHP and JavaScript commands
Derek Jones37f4b9c2011-07-01 17:56:50 -0500462 * that are disallowed. Rather than removing the
Derek Jonese701d762010-03-02 18:17:01 -0600463 * code, it simply converts the parenthesis to entities
464 * rendering the code un-executable.
465 *
466 * For example: eval('some code')
467 * Becomes: eval&#40;'some code'&#41;
Derek Jonese701d762010-03-02 18:17:01 -0600468 */
469 $str = preg_replace('#(alert|cmd|passthru|eval|exec|expression|system|fopen|fsockopen|file|file_get_contents|readfile|unlink)(\s*)\((.*?)\)#si', "\\1\\2&#40;\\3&#41;", $str);
Barry Mienydd671972010-10-04 16:33:58 +0200470
Barry Mienydd671972010-10-04 16:33:58 +0200471
Pascal Krietec9c045a2011-04-05 14:50:41 -0400472 // Final clean up
473 // This adds a bit of extra precaution in case
474 // something got through the above filters
475 $str = $this->_do_never_allowed($str);
Derek Jonese701d762010-03-02 18:17:01 -0600476
477 /*
Pascal Krietec9c045a2011-04-05 14:50:41 -0400478 * Images are Handled in a Special Way
David Behler07b53422011-08-15 00:25:06 +0200479 * - Essentially, we want to know that after all of the character
480 * conversion is done whether any unwanted, likely XSS, code was found.
Pascal Krietec9c045a2011-04-05 14:50:41 -0400481 * If not, we return TRUE, as the image is clean.
David Behler07b53422011-08-15 00:25:06 +0200482 * However, if the string post-conversion does not matched the
483 * string post-removal of XSS, then it fails, as there was unwanted XSS
Pascal Krietec9c045a2011-04-05 14:50:41 -0400484 * code found and removed/changed during processing.
Derek Jonese701d762010-03-02 18:17:01 -0600485 */
486
487 if ($is_image === TRUE)
488 {
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300489 return ($str === $converted_string) ? TRUE : FALSE;
Derek Jonese701d762010-03-02 18:17:01 -0600490 }
Barry Mienydd671972010-10-04 16:33:58 +0200491
Derek Jonese701d762010-03-02 18:17:01 -0600492 log_message('debug', "XSS Filtering completed");
493 return $str;
494 }
495
496 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200497
Derek Jonese701d762010-03-02 18:17:01 -0600498 /**
499 * Random Hash for protecting URLs
500 *
Derek Jonese701d762010-03-02 18:17:01 -0600501 * @return string
502 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500503 public function xss_hash()
Barry Mienydd671972010-10-04 16:33:58 +0200504 {
Pascal Krietec9c045a2011-04-05 14:50:41 -0400505 if ($this->_xss_hash == '')
Derek Jonese701d762010-03-02 18:17:01 -0600506 {
Pascal Krietec38e3b62011-11-14 13:55:00 -0500507 mt_srand();
Pascal Krietec9c045a2011-04-05 14:50:41 -0400508 $this->_xss_hash = md5(time() + mt_rand(0, 1999999999));
Derek Jonese701d762010-03-02 18:17:01 -0600509 }
510
Pascal Krietec9c045a2011-04-05 14:50:41 -0400511 return $this->_xss_hash;
Derek Jonese701d762010-03-02 18:17:01 -0600512 }
513
514 // --------------------------------------------------------------------
515
516 /**
Derek Jonesa0911472010-03-30 10:33:09 -0500517 * HTML Entities Decode
518 *
519 * This function is a replacement for html_entity_decode()
520 *
Pascal Krietec38e3b62011-11-14 13:55:00 -0500521 * The reason we are not using html_entity_decode() by itself is because
522 * while it is not technically correct to leave out the semicolon
523 * at the end of an entity most browsers will still interpret the entity
524 * correctly. html_entity_decode() does not convert entities without
525 * semicolons, so we are left with our own little solution here. Bummer.
Derek Jonesa0911472010-03-30 10:33:09 -0500526 *
Derek Jonesa0911472010-03-30 10:33:09 -0500527 * @param string
528 * @param string
529 * @return string
530 */
freewil8cc0cfe2011-08-27 21:53:00 -0400531 public function entity_decode($str, $charset = NULL)
Derek Jonesa0911472010-03-30 10:33:09 -0500532 {
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300533 if (strpos($str, '&') === FALSE)
freewil5c9b0d12011-08-28 12:15:23 -0400534 {
535 return $str;
536 }
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300537
freewil5c9b0d12011-08-28 12:15:23 -0400538 if (empty($charset))
539 {
540 $charset = config_item('charset');
541 }
Barry Mienydd671972010-10-04 16:33:58 +0200542
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300543 $str = html_entity_decode($str, ENT_COMPAT, $charset);
544 $str = preg_replace('~&#x(0*[0-9a-f]{2,5})~ei', 'chr(hexdec("\\1"))', $str);
545 return preg_replace('~&#([0-9]{2,4})~e', 'chr(\\1)', $str);
Derek Jonesa0911472010-03-30 10:33:09 -0500546 }
Barry Mienydd671972010-10-04 16:33:58 +0200547
Derek Jonesa0911472010-03-30 10:33:09 -0500548 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200549
Derek Jonesa0911472010-03-30 10:33:09 -0500550 /**
Derek Jonese701d762010-03-02 18:17:01 -0600551 * Filename Security
552 *
Derek Jonese701d762010-03-02 18:17:01 -0600553 * @param string
David Behler07b53422011-08-15 00:25:06 +0200554 * @param bool
Derek Jonese701d762010-03-02 18:17:01 -0600555 * @return string
556 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500557 public function sanitize_filename($str, $relative_path = FALSE)
Derek Jonese701d762010-03-02 18:17:01 -0600558 {
559 $bad = array(
560 "../",
Derek Jonese701d762010-03-02 18:17:01 -0600561 "<!--",
562 "-->",
563 "<",
564 ">",
565 "'",
566 '"',
567 '&',
568 '$',
569 '#',
570 '{',
571 '}',
572 '[',
573 ']',
574 '=',
575 ';',
576 '?',
Derek Jonese701d762010-03-02 18:17:01 -0600577 "%20",
578 "%22",
579 "%3c", // <
Barry Mienydd671972010-10-04 16:33:58 +0200580 "%253c", // <
581 "%3e", // >
582 "%0e", // >
583 "%28", // (
584 "%29", // )
585 "%2528", // (
586 "%26", // &
587 "%24", // $
588 "%3f", // ?
589 "%3b", // ;
Derek Jonese701d762010-03-02 18:17:01 -0600590 "%3d" // =
591 );
David Behler07b53422011-08-15 00:25:06 +0200592
Derek Jones2ef37592010-10-06 17:51:59 -0500593 if ( ! $relative_path)
594 {
595 $bad[] = './';
596 $bad[] = '/';
597 }
Derek Jonese701d762010-03-02 18:17:01 -0600598
Pascal Krietec9c045a2011-04-05 14:50:41 -0400599 $str = remove_invisible_characters($str, FALSE);
Derek Jonese701d762010-03-02 18:17:01 -0600600 return stripslashes(str_replace($bad, '', $str));
601 }
602
Pascal Krietec9c045a2011-04-05 14:50:41 -0400603 // ----------------------------------------------------------------
604
605 /**
606 * Compact Exploded Words
607 *
608 * Callback function for xss_clean() to remove whitespace from
609 * things like j a v a s c r i p t
610 *
611 * @param type
612 * @return type
613 */
614 protected function _compact_exploded_words($matches)
615 {
616 return preg_replace('/\s+/s', '', $matches[1]).$matches[2];
617 }
618
619 // --------------------------------------------------------------------
David Behler07b53422011-08-15 00:25:06 +0200620
Pascal Krietec9c045a2011-04-05 14:50:41 -0400621 /*
622 * Remove Evil HTML Attributes (like evenhandlers and style)
623 *
624 * It removes the evil attribute and either:
625 * - Everything up until a space
626 * For example, everything between the pipes:
627 * <a |style=document.write('hello');alert('world');| class=link>
David Behler07b53422011-08-15 00:25:06 +0200628 * - Everything inside the quotes
Pascal Krietec9c045a2011-04-05 14:50:41 -0400629 * For example, everything between the pipes:
630 * <a |style="document.write('hello'); alert('world');"| class="link">
631 *
632 * @param string $str The string to check
633 * @param boolean $is_image TRUE if this is an image
634 * @return string The string with the evil attributes removed
635 */
636 protected function _remove_evil_attributes($str, $is_image)
637 {
638 // All javascript event handlers (e.g. onload, onclick, onmouseover), style, and xmlns
Pascal Krietec38e3b62011-11-14 13:55:00 -0500639 $evil_attributes = array('on\w*', 'style', 'xmlns', 'formaction');
Pascal Krietec9c045a2011-04-05 14:50:41 -0400640
641 if ($is_image === TRUE)
642 {
643 /*
Pascal Krietec38e3b62011-11-14 13:55:00 -0500644 * Adobe Photoshop puts XML metadata into JFIF images,
Pascal Krietec9c045a2011-04-05 14:50:41 -0400645 * including namespacing, so we have to allow this for images.
646 */
647 unset($evil_attributes[array_search('xmlns', $evil_attributes)]);
648 }
Pascal Krietec38e3b62011-11-14 13:55:00 -0500649
Pascal Krietec9c045a2011-04-05 14:50:41 -0400650 do {
Pascal Krietec38e3b62011-11-14 13:55:00 -0500651 $count = 0;
652 $attribs = array();
653
654 // find occurrences of illegal attribute strings without quotes
655 preg_match_all("/(".implode('|', $evil_attributes).")\s*=\s*([^\s]*)/is", $str, $matches, PREG_SET_ORDER);
656
657 foreach ($matches as $attr)
658 {
659 $attribs[] = preg_quote($attr[0], '/');
660 }
661
662 // find occurrences of illegal attribute strings with quotes (042 and 047 are octal quotes)
663 preg_match_all("/(".implode('|', $evil_attributes).")\s*=\s*(\042|\047)([^\\2]*?)(\\2)/is", $str, $matches, PREG_SET_ORDER);
David Behler07b53422011-08-15 00:25:06 +0200664
Pascal Krietec38e3b62011-11-14 13:55:00 -0500665 foreach ($matches as $attr)
666 {
667 $attribs[] = preg_quote($attr[0], '/');
668 }
669
670 // replace illegal attribute strings that are inside an html tag
671 if (count($attribs) > 0)
672 {
673 $str = preg_replace("/<(\/?[^><]+?)([^A-Za-z\-])(".implode('|', $attribs).")([\s><])([><]*)/i", '<$1$2$4$5', $str, -1, $count);
674 }
675
676 } while ($count);
677
Pascal Krietec9c045a2011-04-05 14:50:41 -0400678 return $str;
679 }
David Behler07b53422011-08-15 00:25:06 +0200680
Pascal Krietec9c045a2011-04-05 14:50:41 -0400681 // --------------------------------------------------------------------
682
683 /**
684 * Sanitize Naughty HTML
685 *
686 * Callback function for xss_clean() to remove naughty HTML elements
687 *
688 * @param array
689 * @return string
690 */
691 protected function _sanitize_naughty_html($matches)
692 {
693 // encode opening brace
694 $str = '&lt;'.$matches[1].$matches[2].$matches[3];
695
696 // encode captured opening or closing brace to prevent recursive vectors
David Behler07b53422011-08-15 00:25:06 +0200697 $str .= str_replace(array('>', '<'), array('&gt;', '&lt;'),
Pascal Krietec9c045a2011-04-05 14:50:41 -0400698 $matches[4]);
699
700 return $str;
701 }
702
703 // --------------------------------------------------------------------
704
705 /**
706 * JS Link Removal
707 *
708 * Callback function for xss_clean() to sanitize links
709 * This limits the PCRE backtracks, making it more performance friendly
710 * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in
711 * PHP 5.2+ on link-heavy strings
712 *
713 * @param array
714 * @return string
715 */
716 protected function _js_link_removal($match)
717 {
718 $attributes = $this->_filter_attributes(str_replace(array('<', '>'), '', $match[1]));
David Behler07b53422011-08-15 00:25:06 +0200719
Pascal Krietec9c045a2011-04-05 14:50:41 -0400720 return str_replace($match[1], preg_replace("#href=.*?(alert\(|alert&\#40;|javascript\:|livescript\:|mocha\:|charset\=|window\.|document\.|\.cookie|<script|<xss|base64\s*,)#si", "", $attributes), $match[0]);
721 }
722
723 // --------------------------------------------------------------------
724
725 /**
726 * JS Image Removal
727 *
728 * Callback function for xss_clean() to sanitize image tags
729 * This limits the PCRE backtracks, making it more performance friendly
730 * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in
731 * PHP 5.2+ on image tag heavy strings
732 *
733 * @param array
734 * @return string
735 */
736 protected function _js_img_removal($match)
737 {
738 $attributes = $this->_filter_attributes(str_replace(array('<', '>'), '', $match[1]));
David Behler07b53422011-08-15 00:25:06 +0200739
Pascal Krietec9c045a2011-04-05 14:50:41 -0400740 return str_replace($match[1], preg_replace("#src=.*?(alert\(|alert&\#40;|javascript\:|livescript\:|mocha\:|charset\=|window\.|document\.|\.cookie|<script|<xss|base64\s*,)#si", "", $attributes), $match[0]);
741 }
742
743 // --------------------------------------------------------------------
744
745 /**
746 * Attribute Conversion
747 *
748 * Used as a callback for XSS Clean
749 *
750 * @param array
751 * @return string
752 */
753 protected function _convert_attribute($match)
754 {
755 return str_replace(array('>', '<', '\\'), array('&gt;', '&lt;', '\\\\'), $match[0]);
756 }
757
758 // --------------------------------------------------------------------
759
760 /**
761 * Filter Attributes
762 *
763 * Filters tag attributes for consistency and safety
764 *
765 * @param string
766 * @return string
767 */
768 protected function _filter_attributes($str)
769 {
770 $out = '';
771
772 if (preg_match_all('#\s*[a-z\-]+\s*=\s*(\042|\047)([^\\1]*?)\\1#is', $str, $matches))
773 {
774 foreach ($matches[0] as $match)
775 {
776 $out .= preg_replace("#/\*.*?\*/#s", '', $match);
777 }
778 }
779
780 return $out;
781 }
782
783 // --------------------------------------------------------------------
784
785 /**
786 * HTML Entity Decode Callback
787 *
788 * Used as a callback for XSS Clean
789 *
790 * @param array
791 * @return string
792 */
793 protected function _decode_entity($match)
794 {
795 return $this->entity_decode($match[0], strtoupper(config_item('charset')));
796 }
797
798 // --------------------------------------------------------------------
David Behler07b53422011-08-15 00:25:06 +0200799
Pascal Krietec9c045a2011-04-05 14:50:41 -0400800 /**
801 * Validate URL entities
802 *
803 * Called by xss_clean()
804 *
David Behler07b53422011-08-15 00:25:06 +0200805 * @param string
Pascal Krietec9c045a2011-04-05 14:50:41 -0400806 * @return string
807 */
808 protected function _validate_entities($str)
809 {
810 /*
811 * Protect GET variables in URLs
812 */
David Behler07b53422011-08-15 00:25:06 +0200813
Pascal Krietec9c045a2011-04-05 14:50:41 -0400814 // 901119URL5918AMP18930PROTECT8198
David Behler07b53422011-08-15 00:25:06 +0200815
Pascal Krietec9c045a2011-04-05 14:50:41 -0400816 $str = preg_replace('|\&([a-z\_0-9\-]+)\=([a-z\_0-9\-]+)|i', $this->xss_hash()."\\1=\\2", $str);
817
818 /*
819 * Validate standard character entities
820 *
Derek Jones37f4b9c2011-07-01 17:56:50 -0500821 * Add a semicolon if missing. We do this to enable
Pascal Krietec9c045a2011-04-05 14:50:41 -0400822 * the conversion of entities to ASCII later.
823 *
824 */
825 $str = preg_replace('#(&\#?[0-9a-z]{2,})([\x00-\x20])*;?#i', "\\1;\\2", $str);
826
827 /*
828 * Validate UTF16 two byte encoding (x00)
829 *
830 * Just as above, adds a semicolon if missing.
831 *
832 */
833 $str = preg_replace('#(&\#x?)([0-9A-F]+);?#i',"\\1\\2;",$str);
834
835 /*
836 * Un-Protect GET variables in URLs
837 */
838 $str = str_replace($this->xss_hash(), '&', $str);
David Behler07b53422011-08-15 00:25:06 +0200839
Pascal Krietec9c045a2011-04-05 14:50:41 -0400840 return $str;
841 }
842
843 // ----------------------------------------------------------------------
844
845 /**
846 * Do Never Allowed
847 *
848 * A utility function for xss_clean()
849 *
850 * @param string
851 * @return string
852 */
853 protected function _do_never_allowed($str)
854 {
855 foreach ($this->_never_allowed_str as $key => $val)
856 {
857 $str = str_replace($key, $val, $str);
858 }
859
860 foreach ($this->_never_allowed_regex as $key => $val)
861 {
862 $str = preg_replace("#".$key."#i", $val, $str);
863 }
David Behler07b53422011-08-15 00:25:06 +0200864
Pascal Krietec9c045a2011-04-05 14:50:41 -0400865 return $str;
866 }
867
868 // --------------------------------------------------------------------
869
870 /**
871 * Set Cross Site Request Forgery Protection Cookie
872 *
873 * @return string
874 */
875 protected function _csrf_set_hash()
876 {
877 if ($this->_csrf_hash == '')
878 {
David Behler07b53422011-08-15 00:25:06 +0200879 // If the cookie exists we will use it's value.
Pascal Krietec9c045a2011-04-05 14:50:41 -0400880 // We don't necessarily want to regenerate it with
David Behler07b53422011-08-15 00:25:06 +0200881 // each page load since a page could contain embedded
Pascal Krietec9c045a2011-04-05 14:50:41 -0400882 // sub-pages causing this feature to fail
David Behler07b53422011-08-15 00:25:06 +0200883 if (isset($_COOKIE[$this->_csrf_cookie_name]) &&
Pascal Krietec9c045a2011-04-05 14:50:41 -0400884 $_COOKIE[$this->_csrf_cookie_name] != '')
885 {
886 return $this->_csrf_hash = $_COOKIE[$this->_csrf_cookie_name];
887 }
David Behler07b53422011-08-15 00:25:06 +0200888
Chris Berthed93e6f32011-09-25 10:33:25 -0400889 $this->_csrf_hash = md5(uniqid(rand(), TRUE));
890 $this->csrf_set_cookie();
Pascal Krietec9c045a2011-04-05 14:50:41 -0400891 }
892
893 return $this->_csrf_hash;
894 }
895
Derek Jonese701d762010-03-02 18:17:01 -0600896}
Derek Jonese701d762010-03-02 18:17:01 -0600897
898/* End of file Security.php */
Phil Sturgeonc00a5a02011-11-22 15:25:32 +0000899/* Location: ./system/core/Security.php */