blob: e99418bdd4a51410b589daa6a6f983abdd3c930f [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 *
7 * @package CodeIgniter
8 * @author ExpressionEngine Dev Team
Greg Aker0711dc82011-01-05 10:49:40 -06009 * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
Derek Jonese701d762010-03-02 18:17:01 -060010 * @license http://codeigniter.com/user_guide/license.html
11 * @link http://codeigniter.com
12 * @since Version 1.0
13 * @filesource
14 */
15
16// ------------------------------------------------------------------------
17
18/**
19 * Security Class
20 *
21 * @package CodeIgniter
22 * @subpackage Libraries
23 * @category Security
24 * @author ExpressionEngine Dev Team
Pascal Krietec9c045a2011-04-05 14:50:41 -040025 * @link http://codeigniter.com/user_guide/libraries/security.html
Derek Jonese701d762010-03-02 18:17:01 -060026 */
27class CI_Security {
Barry Mienydd671972010-10-04 16:33:58 +020028
David Behler07b53422011-08-15 00:25:06 +020029 /**
30 * Random Hash for protecting URLs
31 *
32 * @var string
33 * @access protected
34 */
35 protected $_xss_hash = '';
Eric Barnesc6962532011-08-24 23:19:49 -040036
David Behler07b53422011-08-15 00:25:06 +020037 /**
38 * Random Hash for Cross Site Request Forgery Protection Cookie
39 *
40 * @var string
41 * @access protected
42 */
43 protected $_csrf_hash = '';
Eric Barnesc6962532011-08-24 23:19:49 -040044
David Behler07b53422011-08-15 00:25:06 +020045 /**
46 * Expiration time for Cross Site Request Forgery Protection Cookie
47 * Defaults to two hours (in seconds)
48 *
49 * @var int
50 * @access protected
51 */
52 protected $_csrf_expire = 7200;
Eric Barnesc6962532011-08-24 23:19:49 -040053
David Behler07b53422011-08-15 00:25:06 +020054 /**
55 * Token name for Cross Site Request Forgery Protection Cookie
56 *
57 * @var string
58 * @access protected
59 */
60 protected $_csrf_token_name = 'ci_csrf_token';
Eric Barnesc6962532011-08-24 23:19:49 -040061
David Behler07b53422011-08-15 00:25:06 +020062 /**
63 * Cookie name for Cross Site Request Forgery Protection Cookie
64 *
65 * @var string
66 * @access protected
67 */
68 protected $_csrf_cookie_name = 'ci_csrf_token';
Eric Barnesc6962532011-08-24 23:19:49 -040069
David Behler07b53422011-08-15 00:25:06 +020070 /**
71 * List of never allowed strings
72 *
73 * @var array
74 * @access protected
75 */
Eric Barnesc6962532011-08-24 23:19:49 -040076
Pascal Krietec9c045a2011-04-05 14:50:41 -040077 protected $_never_allowed_str = array(
78 'document.cookie' => '[removed]',
79 'document.write' => '[removed]',
80 '.parentNode' => '[removed]',
81 '.innerHTML' => '[removed]',
82 'window.location' => '[removed]',
83 '-moz-binding' => '[removed]',
84 '<!--' => '&lt;!--',
85 '-->' => '--&gt;',
86 '<![CDATA[' => '&lt;![CDATA['
87 );
Derek Jonese701d762010-03-02 18:17:01 -060088
David Behler07b53422011-08-15 00:25:06 +020089 /**
90 * List of never allowed regex replacement
91 *
92 * @var array
93 * @access protected
94 */
Pascal Krietec9c045a2011-04-05 14:50:41 -040095 protected $_never_allowed_regex = array(
96 "javascript\s*:" => '[removed]',
97 "expression\s*(\(|&\#40;)" => '[removed]', // CSS and IE
98 "vbscript\s*:" => '[removed]', // IE, surprise!
99 "Redirect\s+302" => '[removed]'
100 );
David Behler07b53422011-08-15 00:25:06 +0200101
Pascal Krietec9c045a2011-04-05 14:50:41 -0400102 /**
103 * Constructor
104 */
Greg Akera9263282010-11-10 15:26:43 -0600105 public function __construct()
Derek Jonese701d762010-03-02 18:17:01 -0600106 {
patworkef1a55a2011-04-09 13:04:06 +0200107 // CSRF config
108 foreach(array('csrf_expire', 'csrf_token_name', 'csrf_cookie_name') as $key)
109 {
110 if (FALSE !== ($val = config_item($key)))
111 {
112 $this->{'_'.$key} = $val;
113 }
114 }
115
patwork9e267982011-04-11 13:02:32 +0200116 // Append application specific cookie prefix
Greg Akerb3e614d2011-04-19 20:19:17 -0500117 if (config_item('cookie_prefix'))
118 {
patwork9e267982011-04-11 13:02:32 +0200119 $this->_csrf_cookie_name = config_item('cookie_prefix').$this->_csrf_cookie_name;
120 }
Derek Jonesb3f10a22010-07-25 19:11:26 -0500121
Derek Jonese701d762010-03-02 18:17:01 -0600122 // Set the CSRF hash
123 $this->_csrf_set_hash();
Derek Allard958543a2010-07-22 14:10:26 -0400124
Derek Jonese701d762010-03-02 18:17:01 -0600125 log_message('debug', "Security Class Initialized");
126 }
127
128 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200129
Derek Jonese701d762010-03-02 18:17:01 -0600130 /**
131 * Verify Cross Site Request Forgery Protection
132 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400133 * @return object
Derek Jonese701d762010-03-02 18:17:01 -0600134 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500135 public function csrf_verify()
Derek Allard958543a2010-07-22 14:10:26 -0400136 {
Derek Jonese701d762010-03-02 18:17:01 -0600137 // If no POST data exists we will set the CSRF cookie
138 if (count($_POST) == 0)
139 {
140 return $this->csrf_set_cookie();
141 }
Alex Bilbieaeb2c3e2011-08-21 16:14:54 +0100142
143 // Check if URI has been whitelisted from CSRF checks
144 if ($exclude_uris = config_item('csrf_exclude_uris'))
145 {
146 $uri = load_class('URI', 'core');
147 if (in_array($uri->uri_string(), $exclude_uris))
148 {
149 return $this;
150 }
151 }
Derek Jonese701d762010-03-02 18:17:01 -0600152
153 // Do the tokens exist in both the _POST and _COOKIE arrays?
David Behler07b53422011-08-15 00:25:06 +0200154 if ( ! isset($_POST[$this->_csrf_token_name]) OR
Pascal Krietec9c045a2011-04-05 14:50:41 -0400155 ! isset($_COOKIE[$this->_csrf_cookie_name]))
Derek Jonese701d762010-03-02 18:17:01 -0600156 {
157 $this->csrf_show_error();
158 }
159
160 // Do the tokens match?
Pascal Krietec9c045a2011-04-05 14:50:41 -0400161 if ($_POST[$this->_csrf_token_name] != $_COOKIE[$this->_csrf_cookie_name])
Derek Jonese701d762010-03-02 18:17:01 -0600162 {
163 $this->csrf_show_error();
164 }
165
David Behler07b53422011-08-15 00:25:06 +0200166 // We kill this since we're done and we don't want to
Pascal Krietec9c045a2011-04-05 14:50:41 -0400167 // polute the _POST array
168 unset($_POST[$this->_csrf_token_name]);
Barry Mienydd671972010-10-04 16:33:58 +0200169
Derek Jonesb3f10a22010-07-25 19:11:26 -0500170 // Nothing should last forever
Pascal Krietec9c045a2011-04-05 14:50:41 -0400171 unset($_COOKIE[$this->_csrf_cookie_name]);
Derek Jonesb3f10a22010-07-25 19:11:26 -0500172 $this->_csrf_set_hash();
173 $this->csrf_set_cookie();
Eric Barnesc6962532011-08-24 23:19:49 -0400174
Alex Bilbieaeb2c3e2011-08-21 16:14:54 +0100175 log_message('debug', "CSRF token verified");
Derek Jones4b9c6292011-07-01 17:40:48 -0500176
Pascal Krietec9c045a2011-04-05 14:50:41 -0400177 return $this;
Derek Jonese701d762010-03-02 18:17:01 -0600178 }
Barry Mienydd671972010-10-04 16:33:58 +0200179
Derek Jonese701d762010-03-02 18:17:01 -0600180 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200181
Derek Jonese701d762010-03-02 18:17:01 -0600182 /**
183 * Set Cross Site Request Forgery Protection Cookie
184 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400185 * @return object
Derek Jonese701d762010-03-02 18:17:01 -0600186 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500187 public function csrf_set_cookie()
Derek Jonese701d762010-03-02 18:17:01 -0600188 {
Pascal Krietec9c045a2011-04-05 14:50:41 -0400189 $expire = time() + $this->_csrf_expire;
Robin Sowell154da112011-02-11 15:33:44 -0500190 $secure_cookie = (config_item('cookie_secure') === TRUE) ? 1 : 0;
Derek Jonese701d762010-03-02 18:17:01 -0600191
Pascal Krietec9c045a2011-04-05 14:50:41 -0400192 if ($secure_cookie)
Derek Jonese701d762010-03-02 18:17:01 -0600193 {
Pascal Krietec9c045a2011-04-05 14:50:41 -0400194 $req = isset($_SERVER['HTTPS']) ? $_SERVER['HTTPS'] : FALSE;
195
196 if ( ! $req OR $req == 'off')
Derek Jonese701d762010-03-02 18:17:01 -0600197 {
Pascal Krietec9c045a2011-04-05 14:50:41 -0400198 return FALSE;
Derek Jonese701d762010-03-02 18:17:01 -0600199 }
200 }
Derek Allard958543a2010-07-22 14:10:26 -0400201
Pascal Krietec9c045a2011-04-05 14:50:41 -0400202 setcookie($this->_csrf_cookie_name, $this->_csrf_hash, $expire, config_item('cookie_path'), config_item('cookie_domain'), $secure_cookie);
203
204 log_message('debug', "CRSF cookie Set");
David Behler07b53422011-08-15 00:25:06 +0200205
Pascal Krietec9c045a2011-04-05 14:50:41 -0400206 return $this;
Derek Jonese701d762010-03-02 18:17:01 -0600207 }
208
209 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200210
Derek Jonese701d762010-03-02 18:17:01 -0600211 /**
212 * Show CSRF Error
213 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400214 * @return void
Derek Jonese701d762010-03-02 18:17:01 -0600215 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500216 public function csrf_show_error()
Derek Jonese701d762010-03-02 18:17:01 -0600217 {
218 show_error('The action you have requested is not allowed.');
219 }
220
221 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200222
Derek Jonese701d762010-03-02 18:17:01 -0600223 /**
David Behler07b53422011-08-15 00:25:06 +0200224 * Get CSRF Hash
Pascal Krietec9c045a2011-04-05 14:50:41 -0400225 *
David Behler07b53422011-08-15 00:25:06 +0200226 * Getter Method
Pascal Krietec9c045a2011-04-05 14:50:41 -0400227 *
228 * @return string self::_csrf_hash
229 */
230 public function get_csrf_hash()
231 {
232 return $this->_csrf_hash;
233 }
234
235 // --------------------------------------------------------------------
236
237 /**
238 * Get CSRF Token Name
239 *
240 * Getter Method
241 *
242 * @return string self::csrf_token_name
243 */
244 public function get_csrf_token_name()
245 {
246 return $this->_csrf_token_name;
247 }
248
249 // --------------------------------------------------------------------
250
251 /**
Derek Jonese701d762010-03-02 18:17:01 -0600252 * XSS Clean
253 *
254 * Sanitizes data so that Cross Site Scripting Hacks can be
Derek Jones37f4b9c2011-07-01 17:56:50 -0500255 * prevented. This function does a fair amount of work but
Derek Jonese701d762010-03-02 18:17:01 -0600256 * it is extremely thorough, designed to prevent even the
Derek Jones37f4b9c2011-07-01 17:56:50 -0500257 * most obscure XSS attempts. Nothing is ever 100% foolproof,
Derek Jonese701d762010-03-02 18:17:01 -0600258 * of course, but I haven't been able to get anything passed
259 * the filter.
260 *
261 * Note: This function should only be used to deal with data
Derek Jones37f4b9c2011-07-01 17:56:50 -0500262 * upon submission. It's not something that should
Derek Jonese701d762010-03-02 18:17:01 -0600263 * be used for general runtime processing.
264 *
265 * This function was based in part on some code and ideas I
266 * got from Bitflux: http://channel.bitflux.ch/wiki/XSS_Prevention
267 *
268 * To help develop this script I used this great list of
269 * vulnerabilities along with a few other hacks I've
270 * harvested from examining vulnerabilities in other programs:
271 * http://ha.ckers.org/xss.html
272 *
Derek Jonese701d762010-03-02 18:17:01 -0600273 * @param mixed string or array
David Behler07b53422011-08-15 00:25:06 +0200274 * @param bool
Derek Jonese701d762010-03-02 18:17:01 -0600275 * @return string
276 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500277 public function xss_clean($str, $is_image = FALSE)
Derek Jonese701d762010-03-02 18:17:01 -0600278 {
279 /*
280 * Is the string an array?
281 *
282 */
283 if (is_array($str))
284 {
285 while (list($key) = each($str))
286 {
287 $str[$key] = $this->xss_clean($str[$key]);
288 }
Barry Mienydd671972010-10-04 16:33:58 +0200289
Derek Jonese701d762010-03-02 18:17:01 -0600290 return $str;
291 }
292
293 /*
294 * Remove Invisible Characters
295 */
Greg Aker757dda62010-04-14 19:06:19 -0500296 $str = remove_invisible_characters($str);
Derek Jonese701d762010-03-02 18:17:01 -0600297
Pascal Krietec9c045a2011-04-05 14:50:41 -0400298 // Validate Entities in URLs
299 $str = $this->_validate_entities($str);
Derek Jonese701d762010-03-02 18:17:01 -0600300
301 /*
302 * URL Decode
303 *
304 * Just in case stuff like this is submitted:
305 *
306 * <a href="http://%77%77%77%2E%67%6F%6F%67%6C%65%2E%63%6F%6D">Google</a>
307 *
308 * Note: Use rawurldecode() so it does not remove plus signs
309 *
310 */
311 $str = rawurldecode($str);
Barry Mienydd671972010-10-04 16:33:58 +0200312
Derek Jonese701d762010-03-02 18:17:01 -0600313 /*
Barry Mienydd671972010-10-04 16:33:58 +0200314 * Convert character entities to ASCII
Derek Jonese701d762010-03-02 18:17:01 -0600315 *
316 * This permits our tests below to work reliably.
317 * We only convert entities that are within tags since
318 * these are the ones that will pose security problems.
319 *
320 */
321
322 $str = preg_replace_callback("/[a-z]+=([\'\"]).*?\\1/si", array($this, '_convert_attribute'), $str);
David Behler07b53422011-08-15 00:25:06 +0200323
Derek Jonese701d762010-03-02 18:17:01 -0600324 $str = preg_replace_callback("/<\w+.*?(?=>|<|$)/si", array($this, '_decode_entity'), $str);
325
326 /*
327 * Remove Invisible Characters Again!
328 */
Greg Aker757dda62010-04-14 19:06:19 -0500329 $str = remove_invisible_characters($str);
Barry Mienydd671972010-10-04 16:33:58 +0200330
Derek Jonese701d762010-03-02 18:17:01 -0600331 /*
332 * Convert all tabs to spaces
333 *
334 * This prevents strings like this: ja vascript
335 * NOTE: we deal with spaces between characters later.
David Behler07b53422011-08-15 00:25:06 +0200336 * NOTE: preg_replace was found to be amazingly slow here on
Pascal Krietec9c045a2011-04-05 14:50:41 -0400337 * large blocks of data, so we use str_replace.
Derek Jonese701d762010-03-02 18:17:01 -0600338 */
Barry Mienydd671972010-10-04 16:33:58 +0200339
Derek Jonese701d762010-03-02 18:17:01 -0600340 if (strpos($str, "\t") !== FALSE)
341 {
342 $str = str_replace("\t", ' ', $str);
343 }
Barry Mienydd671972010-10-04 16:33:58 +0200344
Derek Jonese701d762010-03-02 18:17:01 -0600345 /*
346 * Capture converted string for later comparison
347 */
348 $converted_string = $str;
Barry Mienydd671972010-10-04 16:33:58 +0200349
Pascal Krietec9c045a2011-04-05 14:50:41 -0400350 // Remove Strings that are never allowed
351 $str = $this->_do_never_allowed($str);
Derek Jonese701d762010-03-02 18:17:01 -0600352
353 /*
354 * Makes PHP tags safe
355 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400356 * Note: XML tags are inadvertently replaced too:
Derek Jonese701d762010-03-02 18:17:01 -0600357 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400358 * <?xml
Derek Jonese701d762010-03-02 18:17:01 -0600359 *
360 * But it doesn't seem to pose a problem.
Derek Jonese701d762010-03-02 18:17:01 -0600361 */
362 if ($is_image === TRUE)
363 {
David Behler07b53422011-08-15 00:25:06 +0200364 // Images have a tendency to have the PHP short opening and
365 // closing tags every so often so we skip those and only
Pascal Krietec9c045a2011-04-05 14:50:41 -0400366 // do the long opening tags.
Derek Jonese701d762010-03-02 18:17:01 -0600367 $str = preg_replace('/<\?(php)/i', "&lt;?\\1", $str);
368 }
369 else
370 {
Derek Jones37f4b9c2011-07-01 17:56:50 -0500371 $str = str_replace(array('<?', '?'.'>'), array('&lt;?', '?&gt;'), $str);
Derek Jonese701d762010-03-02 18:17:01 -0600372 }
Barry Mienydd671972010-10-04 16:33:58 +0200373
Derek Jonese701d762010-03-02 18:17:01 -0600374 /*
375 * Compact any exploded words
376 *
Derek Jones37f4b9c2011-07-01 17:56:50 -0500377 * This corrects words like: j a v a s c r i p t
Derek Jonese701d762010-03-02 18:17:01 -0600378 * These words are compacted back to their correct state.
Derek Jonese701d762010-03-02 18:17:01 -0600379 */
Pascal Krietec9c045a2011-04-05 14:50:41 -0400380 $words = array(
David Behler07b53422011-08-15 00:25:06 +0200381 'javascript', 'expression', 'vbscript', 'script',
Pascal Krietec9c045a2011-04-05 14:50:41 -0400382 'applet', 'alert', 'document', 'write', 'cookie', 'window'
383 );
David Behler07b53422011-08-15 00:25:06 +0200384
Derek Jonese701d762010-03-02 18:17:01 -0600385 foreach ($words as $word)
386 {
387 $temp = '';
Barry Mienydd671972010-10-04 16:33:58 +0200388
Derek Jonese701d762010-03-02 18:17:01 -0600389 for ($i = 0, $wordlen = strlen($word); $i < $wordlen; $i++)
390 {
391 $temp .= substr($word, $i, 1)."\s*";
392 }
393
394 // We only want to do this when it is followed by a non-word character
395 // That way valid stuff like "dealer to" does not become "dealerto"
396 $str = preg_replace_callback('#('.substr($temp, 0, -3).')(\W)#is', array($this, '_compact_exploded_words'), $str);
397 }
Barry Mienydd671972010-10-04 16:33:58 +0200398
Derek Jonese701d762010-03-02 18:17:01 -0600399 /*
400 * Remove disallowed Javascript in links or img tags
David Behler07b53422011-08-15 00:25:06 +0200401 * We used to do some version comparisons and use of stripos for PHP5,
402 * but it is dog slow compared to these simplified non-capturing
Pascal Krietec9c045a2011-04-05 14:50:41 -0400403 * preg_match(), especially if the pattern exists in the string
Derek Jonese701d762010-03-02 18:17:01 -0600404 */
405 do
406 {
407 $original = $str;
Barry Mienydd671972010-10-04 16:33:58 +0200408
Derek Jonese701d762010-03-02 18:17:01 -0600409 if (preg_match("/<a/i", $str))
410 {
411 $str = preg_replace_callback("#<a\s+([^>]*?)(>|$)#si", array($this, '_js_link_removal'), $str);
412 }
Barry Mienydd671972010-10-04 16:33:58 +0200413
Derek Jonese701d762010-03-02 18:17:01 -0600414 if (preg_match("/<img/i", $str))
415 {
416 $str = preg_replace_callback("#<img\s+([^>]*?)(\s?/?>|$)#si", array($this, '_js_img_removal'), $str);
417 }
Barry Mienydd671972010-10-04 16:33:58 +0200418
Derek Jonese701d762010-03-02 18:17:01 -0600419 if (preg_match("/script/i", $str) OR preg_match("/xss/i", $str))
420 {
421 $str = preg_replace("#<(/*)(script|xss)(.*?)\>#si", '[removed]', $str);
422 }
423 }
Pascal Krietec9c045a2011-04-05 14:50:41 -0400424 while($original != $str);
Derek Jonese701d762010-03-02 18:17:01 -0600425
426 unset($original);
427
Pascal Krietec9c045a2011-04-05 14:50:41 -0400428 // Remove evil attributes such as style, onclick and xmlns
429 $str = $this->_remove_evil_attributes($str, $is_image);
Barry Mienydd671972010-10-04 16:33:58 +0200430
Derek Jonese701d762010-03-02 18:17:01 -0600431 /*
432 * Sanitize naughty HTML elements
433 *
434 * If a tag containing any of the words in the list
435 * below is found, the tag gets converted to entities.
436 *
437 * So this: <blink>
438 * Becomes: &lt;blink&gt;
Derek Jonese701d762010-03-02 18:17:01 -0600439 */
440 $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';
441 $str = preg_replace_callback('#<(/*\s*)('.$naughty.')([^><]*)([><]*)#is', array($this, '_sanitize_naughty_html'), $str);
442
443 /*
444 * Sanitize naughty scripting elements
445 *
446 * Similar to above, only instead of looking for
447 * tags it looks for PHP and JavaScript commands
Derek Jones37f4b9c2011-07-01 17:56:50 -0500448 * that are disallowed. Rather than removing the
Derek Jonese701d762010-03-02 18:17:01 -0600449 * code, it simply converts the parenthesis to entities
450 * rendering the code un-executable.
451 *
452 * For example: eval('some code')
453 * Becomes: eval&#40;'some code'&#41;
Derek Jonese701d762010-03-02 18:17:01 -0600454 */
455 $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 +0200456
Barry Mienydd671972010-10-04 16:33:58 +0200457
Pascal Krietec9c045a2011-04-05 14:50:41 -0400458 // Final clean up
459 // This adds a bit of extra precaution in case
460 // something got through the above filters
461 $str = $this->_do_never_allowed($str);
Derek Jonese701d762010-03-02 18:17:01 -0600462
463 /*
Pascal Krietec9c045a2011-04-05 14:50:41 -0400464 * Images are Handled in a Special Way
David Behler07b53422011-08-15 00:25:06 +0200465 * - Essentially, we want to know that after all of the character
466 * conversion is done whether any unwanted, likely XSS, code was found.
Pascal Krietec9c045a2011-04-05 14:50:41 -0400467 * If not, we return TRUE, as the image is clean.
David Behler07b53422011-08-15 00:25:06 +0200468 * However, if the string post-conversion does not matched the
469 * string post-removal of XSS, then it fails, as there was unwanted XSS
Pascal Krietec9c045a2011-04-05 14:50:41 -0400470 * code found and removed/changed during processing.
Derek Jonese701d762010-03-02 18:17:01 -0600471 */
472
473 if ($is_image === TRUE)
474 {
Pascal Krietec9c045a2011-04-05 14:50:41 -0400475 return ($str == $converted_string) ? TRUE: FALSE;
Derek Jonese701d762010-03-02 18:17:01 -0600476 }
Barry Mienydd671972010-10-04 16:33:58 +0200477
Derek Jonese701d762010-03-02 18:17:01 -0600478 log_message('debug', "XSS Filtering completed");
479 return $str;
480 }
481
482 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200483
Derek Jonese701d762010-03-02 18:17:01 -0600484 /**
485 * Random Hash for protecting URLs
486 *
Derek Jonese701d762010-03-02 18:17:01 -0600487 * @return string
488 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500489 public function xss_hash()
Barry Mienydd671972010-10-04 16:33:58 +0200490 {
Pascal Krietec9c045a2011-04-05 14:50:41 -0400491 if ($this->_xss_hash == '')
Derek Jonese701d762010-03-02 18:17:01 -0600492 {
493 if (phpversion() >= 4.2)
Derek Jonese701d762010-03-02 18:17:01 -0600494 {
Pascal Krietec9c045a2011-04-05 14:50:41 -0400495 mt_srand();
Derek Jonese701d762010-03-02 18:17:01 -0600496 }
Pascal Krietec9c045a2011-04-05 14:50:41 -0400497 else
498 {
499 mt_srand(hexdec(substr(md5(microtime()), -8)) & 0x7fffffff);
500 }
501
502 $this->_xss_hash = md5(time() + mt_rand(0, 1999999999));
Derek Jonese701d762010-03-02 18:17:01 -0600503 }
504
Pascal Krietec9c045a2011-04-05 14:50:41 -0400505 return $this->_xss_hash;
Derek Jonese701d762010-03-02 18:17:01 -0600506 }
507
508 // --------------------------------------------------------------------
509
510 /**
Derek Jonesa0911472010-03-30 10:33:09 -0500511 * HTML Entities Decode
512 *
513 * This function is a replacement for html_entity_decode()
514 *
515 * In some versions of PHP the native function does not work
516 * when UTF-8 is the specified character set, so this gives us
Derek Jones37f4b9c2011-07-01 17:56:50 -0500517 * a work-around. More info here:
Derek Jonesa0911472010-03-30 10:33:09 -0500518 * http://bugs.php.net/bug.php?id=25670
519 *
520 * NOTE: html_entity_decode() has a bug in some PHP versions when UTF-8 is the
521 * character set, and the PHP developers said they were not back porting the
522 * fix to versions other than PHP 5.x.
523 *
Derek Jonesa0911472010-03-30 10:33:09 -0500524 * @param string
525 * @param string
526 * @return string
527 */
freewil8cc0cfe2011-08-27 21:53:00 -0400528 public function entity_decode($str, $charset = NULL)
Derek Jonesa0911472010-03-30 10:33:09 -0500529 {
freewil5c9b0d12011-08-28 12:15:23 -0400530 if (stristr($str, '&') === FALSE)
531 {
532 return $str;
533 }
534
535 if (empty($charset))
536 {
537 $charset = config_item('charset');
538 }
Barry Mienydd671972010-10-04 16:33:58 +0200539
Derek Jonesa0911472010-03-30 10:33:09 -0500540 // The reason we are not using html_entity_decode() by itself is because
541 // while it is not technically correct to leave out the semicolon
542 // at the end of an entity most browsers will still interpret the entity
Derek Jones37f4b9c2011-07-01 17:56:50 -0500543 // correctly. html_entity_decode() does not convert entities without
Derek Jonesa0911472010-03-30 10:33:09 -0500544 // semicolons, so we are left with our own little solution here. Bummer.
Barry Mienydd671972010-10-04 16:33:58 +0200545
David Behler07b53422011-08-15 00:25:06 +0200546 if (function_exists('html_entity_decode') &&
Pascal Krietec9c045a2011-04-05 14:50:41 -0400547 (strtolower($charset) != 'utf-8'))
Derek Jonesa0911472010-03-30 10:33:09 -0500548 {
549 $str = html_entity_decode($str, ENT_COMPAT, $charset);
550 $str = preg_replace('~&#x(0*[0-9a-f]{2,5})~ei', 'chr(hexdec("\\1"))', $str);
551 return preg_replace('~&#([0-9]{2,4})~e', 'chr(\\1)', $str);
552 }
Barry Mienydd671972010-10-04 16:33:58 +0200553
Derek Jonesa0911472010-03-30 10:33:09 -0500554 // Numeric Entities
555 $str = preg_replace('~&#x(0*[0-9a-f]{2,5});{0,1}~ei', 'chr(hexdec("\\1"))', $str);
556 $str = preg_replace('~&#([0-9]{2,4});{0,1}~e', 'chr(\\1)', $str);
Barry Mienydd671972010-10-04 16:33:58 +0200557
Derek Jonesa0911472010-03-30 10:33:09 -0500558 // Literal Entities - Slightly slow so we do another check
559 if (stristr($str, '&') === FALSE)
560 {
561 $str = strtr($str, array_flip(get_html_translation_table(HTML_ENTITIES)));
562 }
Barry Mienydd671972010-10-04 16:33:58 +0200563
Derek Jonesa0911472010-03-30 10:33:09 -0500564 return $str;
565 }
Barry Mienydd671972010-10-04 16:33:58 +0200566
Derek Jonesa0911472010-03-30 10:33:09 -0500567 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200568
Derek Jonesa0911472010-03-30 10:33:09 -0500569 /**
Derek Jonese701d762010-03-02 18:17:01 -0600570 * Filename Security
571 *
Derek Jonese701d762010-03-02 18:17:01 -0600572 * @param string
David Behler07b53422011-08-15 00:25:06 +0200573 * @param bool
Derek Jonese701d762010-03-02 18:17:01 -0600574 * @return string
575 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500576 public function sanitize_filename($str, $relative_path = FALSE)
Derek Jonese701d762010-03-02 18:17:01 -0600577 {
578 $bad = array(
579 "../",
Derek Jonese701d762010-03-02 18:17:01 -0600580 "<!--",
581 "-->",
582 "<",
583 ">",
584 "'",
585 '"',
586 '&',
587 '$',
588 '#',
589 '{',
590 '}',
591 '[',
592 ']',
593 '=',
594 ';',
595 '?',
Derek Jonese701d762010-03-02 18:17:01 -0600596 "%20",
597 "%22",
598 "%3c", // <
Barry Mienydd671972010-10-04 16:33:58 +0200599 "%253c", // <
600 "%3e", // >
601 "%0e", // >
602 "%28", // (
603 "%29", // )
604 "%2528", // (
605 "%26", // &
606 "%24", // $
607 "%3f", // ?
608 "%3b", // ;
Derek Jonese701d762010-03-02 18:17:01 -0600609 "%3d" // =
610 );
David Behler07b53422011-08-15 00:25:06 +0200611
Derek Jones2ef37592010-10-06 17:51:59 -0500612 if ( ! $relative_path)
613 {
614 $bad[] = './';
615 $bad[] = '/';
616 }
Derek Jonese701d762010-03-02 18:17:01 -0600617
Pascal Krietec9c045a2011-04-05 14:50:41 -0400618 $str = remove_invisible_characters($str, FALSE);
Derek Jonese701d762010-03-02 18:17:01 -0600619 return stripslashes(str_replace($bad, '', $str));
620 }
621
Pascal Krietec9c045a2011-04-05 14:50:41 -0400622 // ----------------------------------------------------------------
623
624 /**
625 * Compact Exploded Words
626 *
627 * Callback function for xss_clean() to remove whitespace from
628 * things like j a v a s c r i p t
629 *
630 * @param type
631 * @return type
632 */
633 protected function _compact_exploded_words($matches)
634 {
635 return preg_replace('/\s+/s', '', $matches[1]).$matches[2];
636 }
637
638 // --------------------------------------------------------------------
David Behler07b53422011-08-15 00:25:06 +0200639
Pascal Krietec9c045a2011-04-05 14:50:41 -0400640 /*
641 * Remove Evil HTML Attributes (like evenhandlers and style)
642 *
643 * It removes the evil attribute and either:
644 * - Everything up until a space
645 * For example, everything between the pipes:
646 * <a |style=document.write('hello');alert('world');| class=link>
David Behler07b53422011-08-15 00:25:06 +0200647 * - Everything inside the quotes
Pascal Krietec9c045a2011-04-05 14:50:41 -0400648 * For example, everything between the pipes:
649 * <a |style="document.write('hello'); alert('world');"| class="link">
650 *
651 * @param string $str The string to check
652 * @param boolean $is_image TRUE if this is an image
653 * @return string The string with the evil attributes removed
654 */
655 protected function _remove_evil_attributes($str, $is_image)
656 {
657 // All javascript event handlers (e.g. onload, onclick, onmouseover), style, and xmlns
658 $evil_attributes = array('on\w*', 'style', 'xmlns');
659
660 if ($is_image === TRUE)
661 {
662 /*
David Behler07b53422011-08-15 00:25:06 +0200663 * Adobe Photoshop puts XML metadata into JFIF images,
Pascal Krietec9c045a2011-04-05 14:50:41 -0400664 * including namespacing, so we have to allow this for images.
665 */
666 unset($evil_attributes[array_search('xmlns', $evil_attributes)]);
667 }
David Behler07b53422011-08-15 00:25:06 +0200668
Pascal Krietec9c045a2011-04-05 14:50:41 -0400669 do {
670 $str = preg_replace(
671 "#<(/?[^><]+?)([^A-Za-z\-])(".implode('|', $evil_attributes).")(\s*=\s*)([\"][^>]*?[\"]|[\'][^>]*?[\']|[^>]*?)([\s><])([><]*)#i",
672 "<$1$6",
673 $str, -1, $count
674 );
675 } while ($count);
David Behler07b53422011-08-15 00:25:06 +0200676
Pascal Krietec9c045a2011-04-05 14:50:41 -0400677 return $str;
678 }
David Behler07b53422011-08-15 00:25:06 +0200679
Pascal Krietec9c045a2011-04-05 14:50:41 -0400680 // --------------------------------------------------------------------
681
682 /**
683 * Sanitize Naughty HTML
684 *
685 * Callback function for xss_clean() to remove naughty HTML elements
686 *
687 * @param array
688 * @return string
689 */
690 protected function _sanitize_naughty_html($matches)
691 {
692 // encode opening brace
693 $str = '&lt;'.$matches[1].$matches[2].$matches[3];
694
695 // encode captured opening or closing brace to prevent recursive vectors
David Behler07b53422011-08-15 00:25:06 +0200696 $str .= str_replace(array('>', '<'), array('&gt;', '&lt;'),
Pascal Krietec9c045a2011-04-05 14:50:41 -0400697 $matches[4]);
698
699 return $str;
700 }
701
702 // --------------------------------------------------------------------
703
704 /**
705 * JS Link Removal
706 *
707 * Callback function for xss_clean() to sanitize links
708 * This limits the PCRE backtracks, making it more performance friendly
709 * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in
710 * PHP 5.2+ on link-heavy strings
711 *
712 * @param array
713 * @return string
714 */
715 protected function _js_link_removal($match)
716 {
717 $attributes = $this->_filter_attributes(str_replace(array('<', '>'), '', $match[1]));
David Behler07b53422011-08-15 00:25:06 +0200718
Pascal Krietec9c045a2011-04-05 14:50:41 -0400719 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]);
720 }
721
722 // --------------------------------------------------------------------
723
724 /**
725 * JS Image Removal
726 *
727 * Callback function for xss_clean() to sanitize image tags
728 * This limits the PCRE backtracks, making it more performance friendly
729 * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in
730 * PHP 5.2+ on image tag heavy strings
731 *
732 * @param array
733 * @return string
734 */
735 protected function _js_img_removal($match)
736 {
737 $attributes = $this->_filter_attributes(str_replace(array('<', '>'), '', $match[1]));
David Behler07b53422011-08-15 00:25:06 +0200738
Pascal Krietec9c045a2011-04-05 14:50:41 -0400739 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]);
740 }
741
742 // --------------------------------------------------------------------
743
744 /**
745 * Attribute Conversion
746 *
747 * Used as a callback for XSS Clean
748 *
749 * @param array
750 * @return string
751 */
752 protected function _convert_attribute($match)
753 {
754 return str_replace(array('>', '<', '\\'), array('&gt;', '&lt;', '\\\\'), $match[0]);
755 }
756
757 // --------------------------------------------------------------------
758
759 /**
760 * Filter Attributes
761 *
762 * Filters tag attributes for consistency and safety
763 *
764 * @param string
765 * @return string
766 */
767 protected function _filter_attributes($str)
768 {
769 $out = '';
770
771 if (preg_match_all('#\s*[a-z\-]+\s*=\s*(\042|\047)([^\\1]*?)\\1#is', $str, $matches))
772 {
773 foreach ($matches[0] as $match)
774 {
775 $out .= preg_replace("#/\*.*?\*/#s", '', $match);
776 }
777 }
778
779 return $out;
780 }
781
782 // --------------------------------------------------------------------
783
784 /**
785 * HTML Entity Decode Callback
786 *
787 * Used as a callback for XSS Clean
788 *
789 * @param array
790 * @return string
791 */
792 protected function _decode_entity($match)
793 {
794 return $this->entity_decode($match[0], strtoupper(config_item('charset')));
795 }
796
797 // --------------------------------------------------------------------
David Behler07b53422011-08-15 00:25:06 +0200798
Pascal Krietec9c045a2011-04-05 14:50:41 -0400799 /**
800 * Validate URL entities
801 *
802 * Called by xss_clean()
803 *
David Behler07b53422011-08-15 00:25:06 +0200804 * @param string
Pascal Krietec9c045a2011-04-05 14:50:41 -0400805 * @return string
806 */
807 protected function _validate_entities($str)
808 {
809 /*
810 * Protect GET variables in URLs
811 */
David Behler07b53422011-08-15 00:25:06 +0200812
Pascal Krietec9c045a2011-04-05 14:50:41 -0400813 // 901119URL5918AMP18930PROTECT8198
David Behler07b53422011-08-15 00:25:06 +0200814
Pascal Krietec9c045a2011-04-05 14:50:41 -0400815 $str = preg_replace('|\&([a-z\_0-9\-]+)\=([a-z\_0-9\-]+)|i', $this->xss_hash()."\\1=\\2", $str);
816
817 /*
818 * Validate standard character entities
819 *
Derek Jones37f4b9c2011-07-01 17:56:50 -0500820 * Add a semicolon if missing. We do this to enable
Pascal Krietec9c045a2011-04-05 14:50:41 -0400821 * the conversion of entities to ASCII later.
822 *
823 */
824 $str = preg_replace('#(&\#?[0-9a-z]{2,})([\x00-\x20])*;?#i', "\\1;\\2", $str);
825
826 /*
827 * Validate UTF16 two byte encoding (x00)
828 *
829 * Just as above, adds a semicolon if missing.
830 *
831 */
832 $str = preg_replace('#(&\#x?)([0-9A-F]+);?#i',"\\1\\2;",$str);
833
834 /*
835 * Un-Protect GET variables in URLs
836 */
837 $str = str_replace($this->xss_hash(), '&', $str);
David Behler07b53422011-08-15 00:25:06 +0200838
Pascal Krietec9c045a2011-04-05 14:50:41 -0400839 return $str;
840 }
841
842 // ----------------------------------------------------------------------
843
844 /**
845 * Do Never Allowed
846 *
847 * A utility function for xss_clean()
848 *
849 * @param string
850 * @return string
851 */
852 protected function _do_never_allowed($str)
853 {
854 foreach ($this->_never_allowed_str as $key => $val)
855 {
856 $str = str_replace($key, $val, $str);
857 }
858
859 foreach ($this->_never_allowed_regex as $key => $val)
860 {
861 $str = preg_replace("#".$key."#i", $val, $str);
862 }
David Behler07b53422011-08-15 00:25:06 +0200863
Pascal Krietec9c045a2011-04-05 14:50:41 -0400864 return $str;
865 }
866
867 // --------------------------------------------------------------------
868
869 /**
870 * Set Cross Site Request Forgery Protection Cookie
871 *
872 * @return string
873 */
874 protected function _csrf_set_hash()
875 {
876 if ($this->_csrf_hash == '')
877 {
David Behler07b53422011-08-15 00:25:06 +0200878 // If the cookie exists we will use it's value.
Pascal Krietec9c045a2011-04-05 14:50:41 -0400879 // We don't necessarily want to regenerate it with
David Behler07b53422011-08-15 00:25:06 +0200880 // each page load since a page could contain embedded
Pascal Krietec9c045a2011-04-05 14:50:41 -0400881 // sub-pages causing this feature to fail
David Behler07b53422011-08-15 00:25:06 +0200882 if (isset($_COOKIE[$this->_csrf_cookie_name]) &&
Pascal Krietec9c045a2011-04-05 14:50:41 -0400883 $_COOKIE[$this->_csrf_cookie_name] != '')
884 {
885 return $this->_csrf_hash = $_COOKIE[$this->_csrf_cookie_name];
886 }
David Behler07b53422011-08-15 00:25:06 +0200887
Pascal Krietec9c045a2011-04-05 14:50:41 -0400888 return $this->_csrf_hash = md5(uniqid(rand(), TRUE));
889 }
890
891 return $this->_csrf_hash;
892 }
893
Derek Jonese701d762010-03-02 18:17:01 -0600894}
Derek Jonese701d762010-03-02 18:17:01 -0600895
896/* End of file Security.php */
Eric Barnesc6962532011-08-24 23:19:49 -0400897/* Location: ./system/libraries/Security.php */