blob: b022947a0f589ec8ac8ec5ba3becc63c02d99e51 [file] [log] [blame]
Derek Jonese701d762010-03-02 18:17:01 -06001<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
2/**
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
9 * @copyright Copyright (c) 2008 - 2010, EllisLab, Inc.
10 * @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
25 * @link http://codeigniter.com/user_guide/libraries/sessions.html
26 */
27class CI_Security {
Eric Barnes9805ecc2011-01-16 23:35:16 -050028
29 public $xss_hash = '';
30 public $csrf_hash = '';
31 public $csrf_expire = 7200; // Two hours (in seconds)
32 public $csrf_token_name = 'ci_csrf_token';
33 public $csrf_cookie_name = 'ci_csrf_token';
Barry Mienydd671972010-10-04 16:33:58 +020034
Derek Jonese701d762010-03-02 18:17:01 -060035 /* never allowed, string replacement */
Eric Barnes9805ecc2011-01-16 23:35:16 -050036 public $never_allowed_str = array(
Derek Jonese701d762010-03-02 18:17:01 -060037 'document.cookie' => '[removed]',
38 'document.write' => '[removed]',
39 '.parentNode' => '[removed]',
40 '.innerHTML' => '[removed]',
41 'window.location' => '[removed]',
42 '-moz-binding' => '[removed]',
43 '<!--' => '&lt;!--',
44 '-->' => '--&gt;',
45 '<![CDATA[' => '&lt;![CDATA['
46 );
47 /* never allowed, regex replacement */
Eric Barnes9805ecc2011-01-16 23:35:16 -050048 public $never_allowed_regex = array(
Derek Jonese701d762010-03-02 18:17:01 -060049 "javascript\s*:" => '[removed]',
50 "expression\s*(\(|&\#40;)" => '[removed]', // CSS and IE
51 "vbscript\s*:" => '[removed]', // IE, surprise!
52 "Redirect\s+302" => '[removed]'
53 );
54
Greg Akera9263282010-11-10 15:26:43 -060055 public function __construct()
Derek Jonese701d762010-03-02 18:17:01 -060056 {
Eric Barnes9805ecc2011-01-16 23:35:16 -050057 $this->csrf_token_name = (config_item('csrf_token_name')) ? config_item('csrf_token_name') : 'csrf_token_name';
58 $this->csrf_cookie_name = (config_item('csrf_cookie_name')) ? config_item('csrf_cookie_name') : 'csrf_cookie_name';
59 $this->csrf_expire = (config_item('csrf_expire')) ? config_item('csrf_expire') : 7200;
60
Derek Jonesb3f10a22010-07-25 19:11:26 -050061 // Append application specific cookie prefix to token name
Derek Jones95b183ad2010-08-31 09:42:39 -050062 $this->csrf_cookie_name = (config_item('cookie_prefix')) ? config_item('cookie_prefix').$this->csrf_token_name : $this->csrf_token_name;
Derek Jonesb3f10a22010-07-25 19:11:26 -050063
Derek Jonese701d762010-03-02 18:17:01 -060064 // Set the CSRF hash
65 $this->_csrf_set_hash();
Derek Allard958543a2010-07-22 14:10:26 -040066
Derek Jonese701d762010-03-02 18:17:01 -060067 log_message('debug', "Security Class Initialized");
68 }
69
70 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +020071
Derek Jonese701d762010-03-02 18:17:01 -060072 /**
73 * Verify Cross Site Request Forgery Protection
74 *
75 * @access public
76 * @return null
77 */
Eric Barnes9805ecc2011-01-16 23:35:16 -050078 public function csrf_verify()
Derek Allard958543a2010-07-22 14:10:26 -040079 {
Derek Jonese701d762010-03-02 18:17:01 -060080 // If no POST data exists we will set the CSRF cookie
81 if (count($_POST) == 0)
82 {
83 return $this->csrf_set_cookie();
84 }
85
86 // Do the tokens exist in both the _POST and _COOKIE arrays?
Derek Jones95b183ad2010-08-31 09:42:39 -050087 if ( ! isset($_POST[$this->csrf_token_name]) OR ! isset($_COOKIE[$this->csrf_cookie_name]))
Derek Jonese701d762010-03-02 18:17:01 -060088 {
89 $this->csrf_show_error();
90 }
91
92 // Do the tokens match?
Derek Jones95b183ad2010-08-31 09:42:39 -050093 if ($_POST[$this->csrf_token_name] != $_COOKIE[$this->csrf_cookie_name])
Derek Jonese701d762010-03-02 18:17:01 -060094 {
95 $this->csrf_show_error();
96 }
97
98 // We kill this since we're done and we don't want to polute the _POST array
99 unset($_POST[$this->csrf_token_name]);
Barry Mienydd671972010-10-04 16:33:58 +0200100
Derek Jonesb3f10a22010-07-25 19:11:26 -0500101 // Nothing should last forever
Derek Jones95b183ad2010-08-31 09:42:39 -0500102 unset($_COOKIE[$this->csrf_cookie_name]);
Derek Jonesb3f10a22010-07-25 19:11:26 -0500103 $this->_csrf_set_hash();
104 $this->csrf_set_cookie();
Derek Jonese701d762010-03-02 18:17:01 -0600105
106 log_message('debug', "CSRF token verified ");
107 }
Barry Mienydd671972010-10-04 16:33:58 +0200108
Derek Jonese701d762010-03-02 18:17:01 -0600109 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200110
Derek Jonese701d762010-03-02 18:17:01 -0600111 /**
112 * Set Cross Site Request Forgery Protection Cookie
113 *
114 * @access public
115 * @return null
116 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500117 public function csrf_set_cookie()
Derek Jonese701d762010-03-02 18:17:01 -0600118 {
Derek Jonese701d762010-03-02 18:17:01 -0600119 $expire = time() + $this->csrf_expire;
120
Derek Jones95b183ad2010-08-31 09:42:39 -0500121 setcookie($this->csrf_cookie_name, $this->csrf_hash, $expire, config_item('cookie_path'), config_item('cookie_domain'), 0);
Barry Mienydd671972010-10-04 16:33:58 +0200122
123 log_message('debug', "CRSF cookie Set");
Derek Jonese701d762010-03-02 18:17:01 -0600124 }
Barry Mienydd671972010-10-04 16:33:58 +0200125
Derek Jonese701d762010-03-02 18:17:01 -0600126 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200127
Derek Jonese701d762010-03-02 18:17:01 -0600128 /**
129 * Set Cross Site Request Forgery Protection Cookie
130 *
Eric Barnes9805ecc2011-01-16 23:35:16 -0500131 * @access private
Derek Jonese701d762010-03-02 18:17:01 -0600132 * @return null
133 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500134 private function _csrf_set_hash()
Derek Jonese701d762010-03-02 18:17:01 -0600135 {
136 if ($this->csrf_hash == '')
137 {
138 // If the cookie exists we will use it's value. We don't necessarily want to regenerate it with
139 // each page load since a page could contain embedded sub-pages causing this feature to fail
Derek Jones95b183ad2010-08-31 09:42:39 -0500140 if (isset($_COOKIE[$this->csrf_cookie_name]) AND $_COOKIE[$this->csrf_cookie_name] != '')
Derek Jonese701d762010-03-02 18:17:01 -0600141 {
Derek Jones95b183ad2010-08-31 09:42:39 -0500142 $this->csrf_hash = $_COOKIE[$this->csrf_cookie_name];
Derek Jonese701d762010-03-02 18:17:01 -0600143 }
144 else
145 {
146 $this->csrf_hash = md5(uniqid(rand(), TRUE));
147 }
148 }
Derek Allard958543a2010-07-22 14:10:26 -0400149
Derek Jonese701d762010-03-02 18:17:01 -0600150 return $this->csrf_hash;
151 }
152
153 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200154
Derek Jonese701d762010-03-02 18:17:01 -0600155 /**
156 * Show CSRF Error
157 *
158 * @access public
159 * @return null
160 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500161 public function csrf_show_error()
Derek Jonese701d762010-03-02 18:17:01 -0600162 {
163 show_error('The action you have requested is not allowed.');
164 }
165
166 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200167
Derek Jonese701d762010-03-02 18:17:01 -0600168 /**
169 * XSS Clean
170 *
171 * Sanitizes data so that Cross Site Scripting Hacks can be
172 * prevented. This function does a fair amount of work but
173 * it is extremely thorough, designed to prevent even the
174 * most obscure XSS attempts. Nothing is ever 100% foolproof,
175 * of course, but I haven't been able to get anything passed
176 * the filter.
177 *
178 * Note: This function should only be used to deal with data
179 * upon submission. It's not something that should
180 * be used for general runtime processing.
181 *
182 * This function was based in part on some code and ideas I
183 * got from Bitflux: http://channel.bitflux.ch/wiki/XSS_Prevention
184 *
185 * To help develop this script I used this great list of
186 * vulnerabilities along with a few other hacks I've
187 * harvested from examining vulnerabilities in other programs:
188 * http://ha.ckers.org/xss.html
189 *
190 * @access public
191 * @param mixed string or array
192 * @return string
193 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500194 public function xss_clean($str, $is_image = FALSE)
Derek Jonese701d762010-03-02 18:17:01 -0600195 {
196 /*
197 * Is the string an array?
198 *
199 */
200 if (is_array($str))
201 {
202 while (list($key) = each($str))
203 {
204 $str[$key] = $this->xss_clean($str[$key]);
205 }
Barry Mienydd671972010-10-04 16:33:58 +0200206
Derek Jonese701d762010-03-02 18:17:01 -0600207 return $str;
208 }
209
210 /*
211 * Remove Invisible Characters
212 */
Greg Aker757dda62010-04-14 19:06:19 -0500213 $str = remove_invisible_characters($str);
Derek Jonese701d762010-03-02 18:17:01 -0600214
215 /*
216 * Protect GET variables in URLs
217 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500218
Derek Jonese701d762010-03-02 18:17:01 -0600219 // 901119URL5918AMP18930PROTECT8198
Eric Barnes9805ecc2011-01-16 23:35:16 -0500220
Derek Jonese701d762010-03-02 18:17:01 -0600221 $str = preg_replace('|\&([a-z\_0-9\-]+)\=([a-z\_0-9\-]+)|i', $this->xss_hash()."\\1=\\2", $str);
222
223 /*
224 * Validate standard character entities
225 *
226 * Add a semicolon if missing. We do this to enable
227 * the conversion of entities to ASCII later.
228 *
229 */
230 $str = preg_replace('#(&\#?[0-9a-z]{2,})([\x00-\x20])*;?#i', "\\1;\\2", $str);
231
232 /*
Barry Mienydd671972010-10-04 16:33:58 +0200233 * Validate UTF16 two byte encoding (x00)
Derek Jonese701d762010-03-02 18:17:01 -0600234 *
235 * Just as above, adds a semicolon if missing.
236 *
237 */
238 $str = preg_replace('#(&\#x?)([0-9A-F]+);?#i',"\\1\\2;",$str);
239
240 /*
241 * Un-Protect GET variables in URLs
242 */
243 $str = str_replace($this->xss_hash(), '&', $str);
244
245 /*
246 * URL Decode
247 *
248 * Just in case stuff like this is submitted:
249 *
250 * <a href="http://%77%77%77%2E%67%6F%6F%67%6C%65%2E%63%6F%6D">Google</a>
251 *
252 * Note: Use rawurldecode() so it does not remove plus signs
253 *
254 */
255 $str = rawurldecode($str);
Barry Mienydd671972010-10-04 16:33:58 +0200256
Derek Jonese701d762010-03-02 18:17:01 -0600257 /*
Barry Mienydd671972010-10-04 16:33:58 +0200258 * Convert character entities to ASCII
Derek Jonese701d762010-03-02 18:17:01 -0600259 *
260 * This permits our tests below to work reliably.
261 * We only convert entities that are within tags since
262 * these are the ones that will pose security problems.
263 *
264 */
265
266 $str = preg_replace_callback("/[a-z]+=([\'\"]).*?\\1/si", array($this, '_convert_attribute'), $str);
Eric Barnes9805ecc2011-01-16 23:35:16 -0500267
Derek Jonese701d762010-03-02 18:17:01 -0600268 $str = preg_replace_callback("/<\w+.*?(?=>|<|$)/si", array($this, '_decode_entity'), $str);
269
270 /*
271 * Remove Invisible Characters Again!
272 */
Greg Aker757dda62010-04-14 19:06:19 -0500273 $str = remove_invisible_characters($str);
Barry Mienydd671972010-10-04 16:33:58 +0200274
Derek Jonese701d762010-03-02 18:17:01 -0600275 /*
276 * Convert all tabs to spaces
277 *
278 * This prevents strings like this: ja vascript
279 * NOTE: we deal with spaces between characters later.
280 * NOTE: preg_replace was found to be amazingly slow here on large blocks of data,
281 * so we use str_replace.
282 *
283 */
Barry Mienydd671972010-10-04 16:33:58 +0200284
Derek Jonese701d762010-03-02 18:17:01 -0600285 if (strpos($str, "\t") !== FALSE)
286 {
287 $str = str_replace("\t", ' ', $str);
288 }
Barry Mienydd671972010-10-04 16:33:58 +0200289
Derek Jonese701d762010-03-02 18:17:01 -0600290 /*
291 * Capture converted string for later comparison
292 */
293 $converted_string = $str;
Barry Mienydd671972010-10-04 16:33:58 +0200294
Derek Jonese701d762010-03-02 18:17:01 -0600295 /*
296 * Not Allowed Under Any Conditions
297 */
Barry Mienydd671972010-10-04 16:33:58 +0200298
Derek Jonese701d762010-03-02 18:17:01 -0600299 foreach ($this->never_allowed_str as $key => $val)
300 {
Barry Mienydd671972010-10-04 16:33:58 +0200301 $str = str_replace($key, $val, $str);
Derek Jonese701d762010-03-02 18:17:01 -0600302 }
Barry Mienydd671972010-10-04 16:33:58 +0200303
Derek Jonese701d762010-03-02 18:17:01 -0600304 foreach ($this->never_allowed_regex as $key => $val)
305 {
Barry Mienydd671972010-10-04 16:33:58 +0200306 $str = preg_replace("#".$key."#i", $val, $str);
Derek Jonese701d762010-03-02 18:17:01 -0600307 }
308
309 /*
310 * Makes PHP tags safe
311 *
312 * Note: XML tags are inadvertently replaced too:
313 *
314 * <?xml
315 *
316 * But it doesn't seem to pose a problem.
317 *
318 */
319 if ($is_image === TRUE)
320 {
321 // Images have a tendency to have the PHP short opening and closing tags every so often
322 // so we skip those and only do the long opening tags.
323 $str = preg_replace('/<\?(php)/i', "&lt;?\\1", $str);
324 }
325 else
326 {
327 $str = str_replace(array('<?', '?'.'>'), array('&lt;?', '?&gt;'), $str);
328 }
Barry Mienydd671972010-10-04 16:33:58 +0200329
Derek Jonese701d762010-03-02 18:17:01 -0600330 /*
331 * Compact any exploded words
332 *
333 * This corrects words like: j a v a s c r i p t
334 * These words are compacted back to their correct state.
335 *
336 */
337 $words = array('javascript', 'expression', 'vbscript', 'script', 'applet', 'alert', 'document', 'write', 'cookie', 'window');
338 foreach ($words as $word)
339 {
340 $temp = '';
Barry Mienydd671972010-10-04 16:33:58 +0200341
Derek Jonese701d762010-03-02 18:17:01 -0600342 for ($i = 0, $wordlen = strlen($word); $i < $wordlen; $i++)
343 {
344 $temp .= substr($word, $i, 1)."\s*";
345 }
346
347 // We only want to do this when it is followed by a non-word character
348 // That way valid stuff like "dealer to" does not become "dealerto"
349 $str = preg_replace_callback('#('.substr($temp, 0, -3).')(\W)#is', array($this, '_compact_exploded_words'), $str);
350 }
Barry Mienydd671972010-10-04 16:33:58 +0200351
Derek Jonese701d762010-03-02 18:17:01 -0600352 /*
353 * Remove disallowed Javascript in links or img tags
354 * We used to do some version comparisons and use of stripos for PHP5, but it is dog slow compared
355 * to these simplified non-capturing preg_match(), especially if the pattern exists in the string
356 */
357 do
358 {
359 $original = $str;
Barry Mienydd671972010-10-04 16:33:58 +0200360
Derek Jonese701d762010-03-02 18:17:01 -0600361 if (preg_match("/<a/i", $str))
362 {
363 $str = preg_replace_callback("#<a\s+([^>]*?)(>|$)#si", array($this, '_js_link_removal'), $str);
364 }
Barry Mienydd671972010-10-04 16:33:58 +0200365
Derek Jonese701d762010-03-02 18:17:01 -0600366 if (preg_match("/<img/i", $str))
367 {
368 $str = preg_replace_callback("#<img\s+([^>]*?)(\s?/?>|$)#si", array($this, '_js_img_removal'), $str);
369 }
Barry Mienydd671972010-10-04 16:33:58 +0200370
Derek Jonese701d762010-03-02 18:17:01 -0600371 if (preg_match("/script/i", $str) OR preg_match("/xss/i", $str))
372 {
373 $str = preg_replace("#<(/*)(script|xss)(.*?)\>#si", '[removed]', $str);
374 }
375 }
376 while($original != $str);
377
378 unset($original);
379
380 /*
381 * Remove JavaScript Event Handlers
382 *
383 * Note: This code is a little blunt. It removes
384 * the event handler and anything up to the closing >,
385 * but it's unlikely to be a problem.
386 *
387 */
388 $event_handlers = array('[^a-z_\-]on\w*','xmlns');
389
390 if ($is_image === TRUE)
391 {
392 /*
Barry Mienydd671972010-10-04 16:33:58 +0200393 * Adobe Photoshop puts XML metadata into JFIF images, including namespacing,
Derek Jonese701d762010-03-02 18:17:01 -0600394 * so we have to allow this for images. -Paul
395 */
396 unset($event_handlers[array_search('xmlns', $event_handlers)]);
397 }
398
399 $str = preg_replace("#<([^><]+?)(".implode('|', $event_handlers).")(\s*=\s*[^><]*)([><]*)#i", "<\\1\\4", $str);
Barry Mienydd671972010-10-04 16:33:58 +0200400
Derek Jonese701d762010-03-02 18:17:01 -0600401 /*
402 * Sanitize naughty HTML elements
403 *
404 * If a tag containing any of the words in the list
405 * below is found, the tag gets converted to entities.
406 *
407 * So this: <blink>
408 * Becomes: &lt;blink&gt;
409 *
410 */
411 $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';
412 $str = preg_replace_callback('#<(/*\s*)('.$naughty.')([^><]*)([><]*)#is', array($this, '_sanitize_naughty_html'), $str);
413
414 /*
415 * Sanitize naughty scripting elements
416 *
417 * Similar to above, only instead of looking for
418 * tags it looks for PHP and JavaScript commands
419 * that are disallowed. Rather than removing the
420 * code, it simply converts the parenthesis to entities
421 * rendering the code un-executable.
422 *
423 * For example: eval('some code')
424 * Becomes: eval&#40;'some code'&#41;
425 *
426 */
427 $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 +0200428
Derek Jonese701d762010-03-02 18:17:01 -0600429 /*
430 * Final clean up
431 *
432 * This adds a bit of extra precaution in case
433 * something got through the above filters
434 *
435 */
436 foreach ($this->never_allowed_str as $key => $val)
437 {
Barry Mienydd671972010-10-04 16:33:58 +0200438 $str = str_replace($key, $val, $str);
Derek Jonese701d762010-03-02 18:17:01 -0600439 }
Barry Mienydd671972010-10-04 16:33:58 +0200440
Derek Jonese701d762010-03-02 18:17:01 -0600441 foreach ($this->never_allowed_regex as $key => $val)
442 {
443 $str = preg_replace("#".$key."#i", $val, $str);
444 }
445
446 /*
447 * Images are Handled in a Special Way
448 * - Essentially, we want to know that after all of the character conversion is done whether
449 * any unwanted, likely XSS, code was found. If not, we return TRUE, as the image is clean.
450 * However, if the string post-conversion does not matched the string post-removal of XSS,
451 * then it fails, as there was unwanted XSS code found and removed/changed during processing.
452 */
453
454 if ($is_image === TRUE)
455 {
456 if ($str == $converted_string)
457 {
458 return TRUE;
459 }
460 else
461 {
462 return FALSE;
463 }
464 }
Barry Mienydd671972010-10-04 16:33:58 +0200465
Derek Jonese701d762010-03-02 18:17:01 -0600466 log_message('debug', "XSS Filtering completed");
467 return $str;
468 }
469
470 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200471
Derek Jonese701d762010-03-02 18:17:01 -0600472 /**
473 * Random Hash for protecting URLs
474 *
475 * @access public
476 * @return string
477 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500478 public function xss_hash()
Barry Mienydd671972010-10-04 16:33:58 +0200479 {
Derek Jonese701d762010-03-02 18:17:01 -0600480 if ($this->xss_hash == '')
481 {
482 if (phpversion() >= 4.2)
483 mt_srand();
484 else
485 mt_srand(hexdec(substr(md5(microtime()), -8)) & 0x7fffffff);
Barry Mienydd671972010-10-04 16:33:58 +0200486
Derek Jonese701d762010-03-02 18:17:01 -0600487 $this->xss_hash = md5(time() + mt_rand(0, 1999999999));
488 }
Barry Mienydd671972010-10-04 16:33:58 +0200489
Derek Jonese701d762010-03-02 18:17:01 -0600490 return $this->xss_hash;
491 }
492
493 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200494
Derek Jonese701d762010-03-02 18:17:01 -0600495 /**
Derek Jonese701d762010-03-02 18:17:01 -0600496 * Compact Exploded Words
497 *
498 * Callback function for xss_clean() to remove whitespace from
499 * things like j a v a s c r i p t
500 *
Eric Barnes9805ecc2011-01-16 23:35:16 -0500501 * @access private
Derek Jonese701d762010-03-02 18:17:01 -0600502 * @param type
503 * @return type
504 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500505 private function _compact_exploded_words($matches)
Derek Jonese701d762010-03-02 18:17:01 -0600506 {
507 return preg_replace('/\s+/s', '', $matches[1]).$matches[2];
508 }
Barry Mienydd671972010-10-04 16:33:58 +0200509
Derek Jonese701d762010-03-02 18:17:01 -0600510 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200511
Derek Jonese701d762010-03-02 18:17:01 -0600512 /**
513 * Sanitize Naughty HTML
514 *
515 * Callback function for xss_clean() to remove naughty HTML elements
516 *
517 * @access private
518 * @param array
519 * @return string
520 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500521 private function _sanitize_naughty_html($matches)
Derek Jonese701d762010-03-02 18:17:01 -0600522 {
523 // encode opening brace
524 $str = '&lt;'.$matches[1].$matches[2].$matches[3];
Barry Mienydd671972010-10-04 16:33:58 +0200525
Derek Jonese701d762010-03-02 18:17:01 -0600526 // encode captured opening or closing brace to prevent recursive vectors
527 $str .= str_replace(array('>', '<'), array('&gt;', '&lt;'), $matches[4]);
Barry Mienydd671972010-10-04 16:33:58 +0200528
Derek Jonese701d762010-03-02 18:17:01 -0600529 return $str;
530 }
Barry Mienydd671972010-10-04 16:33:58 +0200531
Derek Jonese701d762010-03-02 18:17:01 -0600532 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200533
Derek Jonese701d762010-03-02 18:17:01 -0600534 /**
535 * JS Link Removal
536 *
537 * Callback function for xss_clean() to sanitize links
538 * This limits the PCRE backtracks, making it more performance friendly
539 * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in
540 * PHP 5.2+ on link-heavy strings
541 *
542 * @access private
543 * @param array
544 * @return string
545 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500546 private function _js_link_removal($match)
Derek Jonese701d762010-03-02 18:17:01 -0600547 {
548 $attributes = $this->_filter_attributes(str_replace(array('<', '>'), '', $match[1]));
549 return str_replace($match[1], preg_replace("#href=.*?(alert\(|alert&\#40;|javascript\:|charset\=|window\.|document\.|\.cookie|<script|<xss|base64\s*,)#si", "", $attributes), $match[0]);
550 }
Barry Mienydd671972010-10-04 16:33:58 +0200551
Derek Jonese701d762010-03-02 18:17:01 -0600552 /**
553 * JS Image Removal
554 *
555 * Callback function for xss_clean() to sanitize image tags
556 * This limits the PCRE backtracks, making it more performance friendly
557 * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in
558 * PHP 5.2+ on image tag heavy strings
559 *
560 * @access private
561 * @param array
562 * @return string
563 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500564 private function _js_img_removal($match)
Derek Jonese701d762010-03-02 18:17:01 -0600565 {
566 $attributes = $this->_filter_attributes(str_replace(array('<', '>'), '', $match[1]));
567 return str_replace($match[1], preg_replace("#src=.*?(alert\(|alert&\#40;|javascript\:|charset\=|window\.|document\.|\.cookie|<script|<xss|base64\s*,)#si", "", $attributes), $match[0]);
568 }
569
570 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200571
Derek Jonese701d762010-03-02 18:17:01 -0600572 /**
573 * Attribute Conversion
574 *
575 * Used as a callback for XSS Clean
576 *
Eric Barnes9805ecc2011-01-16 23:35:16 -0500577 * @access private
Derek Jonese701d762010-03-02 18:17:01 -0600578 * @param array
579 * @return string
580 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500581 private function _convert_attribute($match)
Derek Jonese701d762010-03-02 18:17:01 -0600582 {
583 return str_replace(array('>', '<', '\\'), array('&gt;', '&lt;', '\\\\'), $match[0]);
584 }
Barry Mienydd671972010-10-04 16:33:58 +0200585
Derek Jonese701d762010-03-02 18:17:01 -0600586 // --------------------------------------------------------------------
587
588 /**
589 * Filter Attributes
590 *
591 * Filters tag attributes for consistency and safety
592 *
Eric Barnes9805ecc2011-01-16 23:35:16 -0500593 * @access private
Derek Jonese701d762010-03-02 18:17:01 -0600594 * @param string
595 * @return string
596 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500597 private function _filter_attributes($str)
Derek Jonese701d762010-03-02 18:17:01 -0600598 {
599 $out = '';
600
601 if (preg_match_all('#\s*[a-z\-]+\s*=\s*(\042|\047)([^\\1]*?)\\1#is', $str, $matches))
602 {
603 foreach ($matches[0] as $match)
604 {
605 $out .= preg_replace("#/\*.*?\*/#s", '', $match);
606 }
607 }
608
609 return $out;
610 }
611
612 // --------------------------------------------------------------------
613
614 /**
615 * HTML Entity Decode Callback
616 *
617 * Used as a callback for XSS Clean
618 *
Eric Barnes9805ecc2011-01-16 23:35:16 -0500619 * @access private
Derek Jonese701d762010-03-02 18:17:01 -0600620 * @param array
621 * @return string
622 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500623 private function _decode_entity($match)
Derek Jonese701d762010-03-02 18:17:01 -0600624 {
Derek Jonesa0911472010-03-30 10:33:09 -0500625 return $this->entity_decode($match[0], strtoupper(config_item('charset')));
Derek Jonese701d762010-03-02 18:17:01 -0600626 }
627
628 // --------------------------------------------------------------------
629
630 /**
Derek Jonesa0911472010-03-30 10:33:09 -0500631 * HTML Entities Decode
632 *
633 * This function is a replacement for html_entity_decode()
634 *
635 * In some versions of PHP the native function does not work
636 * when UTF-8 is the specified character set, so this gives us
637 * a work-around. More info here:
638 * http://bugs.php.net/bug.php?id=25670
639 *
640 * NOTE: html_entity_decode() has a bug in some PHP versions when UTF-8 is the
641 * character set, and the PHP developers said they were not back porting the
642 * fix to versions other than PHP 5.x.
643 *
644 * @access public
645 * @param string
646 * @param string
647 * @return string
648 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500649 public function entity_decode($str, $charset='UTF-8')
Derek Jonesa0911472010-03-30 10:33:09 -0500650 {
651 if (stristr($str, '&') === FALSE) return $str;
Barry Mienydd671972010-10-04 16:33:58 +0200652
Derek Jonesa0911472010-03-30 10:33:09 -0500653 // The reason we are not using html_entity_decode() by itself is because
654 // while it is not technically correct to leave out the semicolon
655 // at the end of an entity most browsers will still interpret the entity
656 // correctly. html_entity_decode() does not convert entities without
657 // semicolons, so we are left with our own little solution here. Bummer.
Barry Mienydd671972010-10-04 16:33:58 +0200658
Derek Jonesa0911472010-03-30 10:33:09 -0500659 if (function_exists('html_entity_decode') && (strtolower($charset) != 'utf-8' OR is_php('5.0.0')))
660 {
661 $str = html_entity_decode($str, ENT_COMPAT, $charset);
662 $str = preg_replace('~&#x(0*[0-9a-f]{2,5})~ei', 'chr(hexdec("\\1"))', $str);
663 return preg_replace('~&#([0-9]{2,4})~e', 'chr(\\1)', $str);
664 }
Barry Mienydd671972010-10-04 16:33:58 +0200665
Derek Jonesa0911472010-03-30 10:33:09 -0500666 // Numeric Entities
667 $str = preg_replace('~&#x(0*[0-9a-f]{2,5});{0,1}~ei', 'chr(hexdec("\\1"))', $str);
668 $str = preg_replace('~&#([0-9]{2,4});{0,1}~e', 'chr(\\1)', $str);
Barry Mienydd671972010-10-04 16:33:58 +0200669
Derek Jonesa0911472010-03-30 10:33:09 -0500670 // Literal Entities - Slightly slow so we do another check
671 if (stristr($str, '&') === FALSE)
672 {
673 $str = strtr($str, array_flip(get_html_translation_table(HTML_ENTITIES)));
674 }
Barry Mienydd671972010-10-04 16:33:58 +0200675
Derek Jonesa0911472010-03-30 10:33:09 -0500676 return $str;
677 }
Barry Mienydd671972010-10-04 16:33:58 +0200678
Derek Jonesa0911472010-03-30 10:33:09 -0500679 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200680
Derek Jonesa0911472010-03-30 10:33:09 -0500681 /**
Derek Jonese701d762010-03-02 18:17:01 -0600682 * Filename Security
683 *
684 * @access public
685 * @param string
686 * @return string
687 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500688 public function sanitize_filename($str, $relative_path = FALSE)
Derek Jonese701d762010-03-02 18:17:01 -0600689 {
690 $bad = array(
691 "../",
Derek Jonese701d762010-03-02 18:17:01 -0600692 "<!--",
693 "-->",
694 "<",
695 ">",
696 "'",
697 '"',
698 '&',
699 '$',
700 '#',
701 '{',
702 '}',
703 '[',
704 ']',
705 '=',
706 ';',
707 '?',
Derek Jonese701d762010-03-02 18:17:01 -0600708 "%20",
709 "%22",
710 "%3c", // <
Barry Mienydd671972010-10-04 16:33:58 +0200711 "%253c", // <
712 "%3e", // >
713 "%0e", // >
714 "%28", // (
715 "%29", // )
716 "%2528", // (
717 "%26", // &
718 "%24", // $
719 "%3f", // ?
720 "%3b", // ;
Derek Jonese701d762010-03-02 18:17:01 -0600721 "%3d" // =
722 );
Eric Barnes9805ecc2011-01-16 23:35:16 -0500723
Derek Jones2ef37592010-10-06 17:51:59 -0500724 if ( ! $relative_path)
725 {
726 $bad[] = './';
727 $bad[] = '/';
728 }
Derek Jonese701d762010-03-02 18:17:01 -0600729
730 return stripslashes(str_replace($bad, '', $str));
731 }
732
733}
734// END Security Class
735
736/* End of file Security.php */
737/* Location: ./system/libraries/Security.php */