blob: e879e2d13eb77b9836c9b3bc1c9d1bbf4f3ab058 [file] [log] [blame]
Derek Allard2067d1a2008-11-13 22:59:24 +00001<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
2/**
3 * CodeIgniter
4 *
5 * An open source application development framework for PHP 4.3.2 or newer
6 *
7 * @package CodeIgniter
8 * @author ExpressionEngine Dev Team
9 * @copyright Copyright (c) 2008, 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 * Input Class
20 *
21 * Pre-processes global input data for security
22 *
23 * @package CodeIgniter
24 * @subpackage Libraries
25 * @category Input
26 * @author ExpressionEngine Dev Team
27 * @link http://codeigniter.com/user_guide/libraries/input.html
28 */
29class CI_Input {
30 var $use_xss_clean = FALSE;
31 var $xss_hash = '';
32 var $ip_address = FALSE;
33 var $user_agent = FALSE;
34 var $allow_get_array = FALSE;
35
36 /* never allowed, string replacement */
37 var $never_allowed_str = array(
38 'document.cookie' => '[removed]',
39 'document.write' => '[removed]',
40 '.parentNode' => '[removed]',
41 '.innerHTML' => '[removed]',
42 'window.location' => '[removed]',
43 '-moz-binding' => '[removed]',
44 '<!--' => '&lt;!--',
45 '-->' => '--&gt;',
46 '<![CDATA[' => '&lt;![CDATA['
47 );
48 /* never allowed, regex replacement */
49 var $never_allowed_regex = array(
Derek Jones9959fed2009-02-04 20:37:40 +000050 "javascript\s*:" => '[removed]',
51 "expression\s*(\(|&\#40;)" => '[removed]', // CSS and IE
52 "vbscript\s*:" => '[removed]', // IE, surprise!
53 "Redirect\s+302" => '[removed]'
Derek Allard2067d1a2008-11-13 22:59:24 +000054 );
55
56 /**
57 * Constructor
58 *
59 * Sets whether to globally enable the XSS processing
60 * and whether to allow the $_GET array
61 *
62 * @access public
63 */
64 function CI_Input()
65 {
66 log_message('debug', "Input Class Initialized");
67
68 $CFG =& load_class('Config');
69 $this->use_xss_clean = ($CFG->item('global_xss_filtering') === TRUE) ? TRUE : FALSE;
70 $this->allow_get_array = ($CFG->item('enable_query_strings') === TRUE) ? TRUE : FALSE;
71 $this->_sanitize_globals();
72 }
73
74 // --------------------------------------------------------------------
75
76 /**
77 * Sanitize Globals
78 *
79 * This function does the following:
80 *
81 * Unsets $_GET data (if query strings are not enabled)
82 *
83 * Unsets all globals if register_globals is enabled
84 *
85 * Standardizes newline characters to \n
86 *
87 * @access private
88 * @return void
89 */
90 function _sanitize_globals()
91 {
92 // Would kind of be "wrong" to unset any of these GLOBALS
93 $protected = array('_SERVER', '_GET', '_POST', '_FILES', '_REQUEST', '_SESSION', '_ENV', 'GLOBALS', 'HTTP_RAW_POST_DATA',
94 'system_folder', 'application_folder', 'BM', 'EXT', 'CFG', 'URI', 'RTR', 'OUT', 'IN');
95
96 // Unset globals for security.
97 // This is effectively the same as register_globals = off
98 foreach (array($_GET, $_POST, $_COOKIE, $_SERVER, $_FILES, $_ENV, (isset($_SESSION) && is_array($_SESSION)) ? $_SESSION : array()) as $global)
99 {
100 if ( ! is_array($global))
101 {
102 if ( ! in_array($global, $protected))
103 {
104 unset($GLOBALS[$global]);
105 }
106 }
107 else
108 {
109 foreach ($global as $key => $val)
110 {
111 if ( ! in_array($key, $protected))
112 {
113 unset($GLOBALS[$key]);
114 }
115
116 if (is_array($val))
117 {
118 foreach($val as $k => $v)
119 {
120 if ( ! in_array($k, $protected))
121 {
122 unset($GLOBALS[$k]);
123 }
124 }
125 }
126 }
127 }
128 }
129
130 // Is $_GET data allowed? If not we'll set the $_GET to an empty array
131 if ($this->allow_get_array == FALSE)
132 {
133 $_GET = array();
134 }
135 else
136 {
137 $_GET = $this->_clean_input_data($_GET);
138 }
139
140 // Clean $_POST Data
141 $_POST = $this->_clean_input_data($_POST);
142
143 // Clean $_COOKIE Data
144 // Also get rid of specially treated cookies that might be set by a server
145 // or silly application, that are of no use to a CI application anyway
146 // but that when present will trip our 'Disallowed Key Characters' alarm
147 // http://www.ietf.org/rfc/rfc2109.txt
148 // note that the key names below are single quoted strings, and are not PHP variables
149 unset($_COOKIE['$Version']);
150 unset($_COOKIE['$Path']);
151 unset($_COOKIE['$Domain']);
152 $_COOKIE = $this->_clean_input_data($_COOKIE);
153
154 log_message('debug', "Global POST and COOKIE data sanitized");
155 }
156
157 // --------------------------------------------------------------------
158
159 /**
160 * Clean Input Data
161 *
162 * This is a helper function. It escapes data and
163 * standardizes newline characters to \n
164 *
165 * @access private
166 * @param string
167 * @return string
168 */
169 function _clean_input_data($str)
170 {
171 if (is_array($str))
172 {
173 $new_array = array();
174 foreach ($str as $key => $val)
175 {
176 $new_array[$this->_clean_input_keys($key)] = $this->_clean_input_data($val);
177 }
178 return $new_array;
179 }
180
181 // We strip slashes if magic quotes is on to keep things consistent
182 if (get_magic_quotes_gpc())
183 {
184 $str = stripslashes($str);
185 }
186
187 // Should we filter the input data?
188 if ($this->use_xss_clean === TRUE)
189 {
190 $str = $this->xss_clean($str);
191 }
192
193 // Standardize newlines
194 if (strpos($str, "\r") !== FALSE)
195 {
196 $str = str_replace(array("\r\n", "\r"), "\n", $str);
197 }
198
199 return $str;
200 }
201
202 // --------------------------------------------------------------------
203
204 /**
205 * Clean Keys
206 *
207 * This is a helper function. To prevent malicious users
208 * from trying to exploit keys we make sure that keys are
209 * only named with alpha-numeric text and a few other items.
210 *
211 * @access private
212 * @param string
213 * @return string
214 */
215 function _clean_input_keys($str)
216 {
217 if ( ! preg_match("/^[a-z0-9:_\/-]+$/i", $str))
218 {
219 exit('Disallowed Key Characters.');
220 }
221
222 return $str;
223 }
224
225 // --------------------------------------------------------------------
226
227 /**
228 * Fetch from array
229 *
230 * This is a helper function to retrieve values from global arrays
231 *
232 * @access private
233 * @param array
234 * @param string
235 * @param bool
236 * @return string
237 */
238 function _fetch_from_array(&$array, $index = '', $xss_clean = FALSE)
239 {
240 if ( ! isset($array[$index]))
241 {
242 return FALSE;
243 }
244
245 if ($xss_clean === TRUE)
246 {
247 return $this->xss_clean($array[$index]);
248 }
249
250 return $array[$index];
251 }
252
253 // --------------------------------------------------------------------
254
255 /**
256 * Fetch an item from the GET array
257 *
258 * @access public
259 * @param string
260 * @param bool
261 * @return string
262 */
263 function get($index = '', $xss_clean = FALSE)
264 {
265 return $this->_fetch_from_array($_GET, $index, $xss_clean);
266 }
267
268 // --------------------------------------------------------------------
269
270 /**
271 * Fetch an item from the POST array
272 *
273 * @access public
274 * @param string
275 * @param bool
276 * @return string
277 */
278 function post($index = '', $xss_clean = FALSE)
279 {
280 return $this->_fetch_from_array($_POST, $index, $xss_clean);
281 }
282
283 // --------------------------------------------------------------------
284
285 /**
286 * Fetch an item from either the GET array or the POST
287 *
288 * @access public
289 * @param string The index key
290 * @param bool XSS cleaning
291 * @return string
292 */
293 function get_post($index = '', $xss_clean = FALSE)
294 {
295 if ( ! isset($_POST[$index]) )
296 {
297 return $this->get($index, $xss_clean);
298 }
299 else
300 {
301 return $this->post($index, $xss_clean);
302 }
303 }
304
305 // --------------------------------------------------------------------
306
307 /**
308 * Fetch an item from the COOKIE array
309 *
310 * @access public
311 * @param string
312 * @param bool
313 * @return string
314 */
315 function cookie($index = '', $xss_clean = FALSE)
316 {
317 return $this->_fetch_from_array($_COOKIE, $index, $xss_clean);
318 }
319
320 // --------------------------------------------------------------------
321
322 /**
323 * Fetch an item from the SERVER array
324 *
325 * @access public
326 * @param string
327 * @param bool
328 * @return string
329 */
330 function server($index = '', $xss_clean = FALSE)
331 {
332 return $this->_fetch_from_array($_SERVER, $index, $xss_clean);
333 }
334
335 // --------------------------------------------------------------------
336
337 /**
338 * Fetch the IP Address
339 *
340 * @access public
341 * @return string
342 */
343 function ip_address()
344 {
345 if ($this->ip_address !== FALSE)
346 {
347 return $this->ip_address;
348 }
349
350 if ($this->server('REMOTE_ADDR') AND $this->server('HTTP_CLIENT_IP'))
351 {
352 $this->ip_address = $_SERVER['HTTP_CLIENT_IP'];
353 }
354 elseif ($this->server('REMOTE_ADDR'))
355 {
356 $this->ip_address = $_SERVER['REMOTE_ADDR'];
357 }
358 elseif ($this->server('HTTP_CLIENT_IP'))
359 {
360 $this->ip_address = $_SERVER['HTTP_CLIENT_IP'];
361 }
362 elseif ($this->server('HTTP_X_FORWARDED_FOR'))
363 {
364 $this->ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
365 }
366
367 if ($this->ip_address === FALSE)
368 {
369 $this->ip_address = '0.0.0.0';
370 return $this->ip_address;
371 }
372
373 if (strstr($this->ip_address, ','))
374 {
375 $x = explode(',', $this->ip_address);
376 $this->ip_address = end($x);
377 }
378
379 if ( ! $this->valid_ip($this->ip_address))
380 {
381 $this->ip_address = '0.0.0.0';
382 }
383
384 return $this->ip_address;
385 }
386
387 // --------------------------------------------------------------------
388
389 /**
390 * Validate IP Address
391 *
392 * Updated version suggested by Geert De Deckere
393 *
394 * @access public
395 * @param string
396 * @return string
397 */
398 function valid_ip($ip)
399 {
400 $ip_segments = explode('.', $ip);
401
402 // Always 4 segments needed
403 if (count($ip_segments) != 4)
404 {
405 return FALSE;
406 }
407 // IP can not start with 0
408 if ($ip_segments[0][0] == '0')
409 {
410 return FALSE;
411 }
412 // Check each segment
413 foreach ($ip_segments as $segment)
414 {
415 // IP segments must be digits and can not be
416 // longer than 3 digits or greater then 255
417 if ($segment == '' OR preg_match("/[^0-9]/", $segment) OR $segment > 255 OR strlen($segment) > 3)
418 {
419 return FALSE;
420 }
421 }
422
423 return TRUE;
424 }
425
426 // --------------------------------------------------------------------
427
428 /**
429 * User Agent
430 *
431 * @access public
432 * @return string
433 */
434 function user_agent()
435 {
436 if ($this->user_agent !== FALSE)
437 {
438 return $this->user_agent;
439 }
440
441 $this->user_agent = ( ! isset($_SERVER['HTTP_USER_AGENT'])) ? FALSE : $_SERVER['HTTP_USER_AGENT'];
442
443 return $this->user_agent;
444 }
445
446 // --------------------------------------------------------------------
447
448 /**
449 * Filename Security
450 *
451 * @access public
452 * @param string
453 * @return string
454 */
455 function filename_security($str)
456 {
457 $bad = array(
458 "../",
459 "./",
460 "<!--",
461 "-->",
462 "<",
463 ">",
464 "'",
465 '"',
466 '&',
467 '$',
468 '#',
469 '{',
470 '}',
471 '[',
472 ']',
473 '=',
474 ';',
475 '?',
476 "%20",
477 "%22",
478 "%3c", // <
479 "%253c", // <
480 "%3e", // >
481 "%0e", // >
482 "%28", // (
483 "%29", // )
484 "%2528", // (
485 "%26", // &
486 "%24", // $
487 "%3f", // ?
488 "%3b", // ;
489 "%3d" // =
490 );
491
492 return stripslashes(str_replace($bad, '', $str));
493 }
494
495 // --------------------------------------------------------------------
496
497 /**
498 * XSS Clean
499 *
500 * Sanitizes data so that Cross Site Scripting Hacks can be
501 * prevented. This function does a fair amount of work but
502 * it is extremely thorough, designed to prevent even the
503 * most obscure XSS attempts. Nothing is ever 100% foolproof,
504 * of course, but I haven't been able to get anything passed
505 * the filter.
506 *
507 * Note: This function should only be used to deal with data
508 * upon submission. It's not something that should
509 * be used for general runtime processing.
510 *
511 * This function was based in part on some code and ideas I
512 * got from Bitflux: http://blog.bitflux.ch/wiki/XSS_Prevention
513 *
514 * To help develop this script I used this great list of
515 * vulnerabilities along with a few other hacks I've
516 * harvested from examining vulnerabilities in other programs:
517 * http://ha.ckers.org/xss.html
518 *
519 * @access public
520 * @param string
521 * @return string
522 */
523 function xss_clean($str, $is_image = FALSE)
524 {
525 /*
526 * Is the string an array?
527 *
528 */
529 if (is_array($str))
530 {
531 while (list($key) = each($str))
532 {
533 $str[$key] = $this->xss_clean($str[$key]);
534 }
535
536 return $str;
537 }
538
539 /*
540 * Remove Invisible Characters
541 */
542 $str = $this->_remove_invisible_characters($str);
543
544 /*
545 * Protect GET variables in URLs
546 */
547
548 // 901119URL5918AMP18930PROTECT8198
549
550 $str = preg_replace('|\&([a-z\_0-9]+)\=([a-z\_0-9]+)|i', $this->xss_hash()."\\1=\\2", $str);
551
552 /*
553 * Validate standard character entities
554 *
555 * Add a semicolon if missing. We do this to enable
556 * the conversion of entities to ASCII later.
557 *
558 */
Derek Jonesab0e31f2008-12-05 22:03:47 +0000559 $str = preg_replace('#(&\#?[0-9a-z]{2,})([\x00-\x20])*;?#i', "\\1;\\2", $str);
Derek Allard2067d1a2008-11-13 22:59:24 +0000560
561 /*
562 * Validate UTF16 two byte encoding (x00)
563 *
564 * Just as above, adds a semicolon if missing.
565 *
566 */
567 $str = preg_replace('#(&\#x?)([0-9A-F]+);?#i',"\\1\\2;",$str);
568
569 /*
570 * Un-Protect GET variables in URLs
571 */
572 $str = str_replace($this->xss_hash(), '&', $str);
573
574 /*
575 * URL Decode
576 *
577 * Just in case stuff like this is submitted:
578 *
579 * <a href="http://%77%77%77%2E%67%6F%6F%67%6C%65%2E%63%6F%6D">Google</a>
580 *
581 * Note: Use rawurldecode() so it does not remove plus signs
582 *
583 */
584 $str = rawurldecode($str);
585
586 /*
587 * Convert character entities to ASCII
588 *
589 * This permits our tests below to work reliably.
590 * We only convert entities that are within tags since
591 * these are the ones that will pose security problems.
592 *
593 */
594
595 $str = preg_replace_callback("/[a-z]+=([\'\"]).*?\\1/si", array($this, '_convert_attribute'), $str);
596
597 $str = preg_replace_callback("/<\w+.*?(?=>|<|$)/si", array($this, '_html_entity_decode_callback'), $str);
598
599 /*
600 * Remove Invisible Characters Again!
601 */
602 $str = $this->_remove_invisible_characters($str);
603
604 /*
605 * Convert all tabs to spaces
606 *
607 * This prevents strings like this: ja vascript
608 * NOTE: we deal with spaces between characters later.
609 * NOTE: preg_replace was found to be amazingly slow here on large blocks of data,
610 * so we use str_replace.
611 *
612 */
613
614 if (strpos($str, "\t") !== FALSE)
615 {
616 $str = str_replace("\t", ' ', $str);
617 }
618
619 /*
620 * Capture converted string for later comparison
621 */
622 $converted_string = $str;
623
624 /*
625 * Not Allowed Under Any Conditions
626 */
627
628 foreach ($this->never_allowed_str as $key => $val)
629 {
630 $str = str_replace($key, $val, $str);
631 }
632
633 foreach ($this->never_allowed_regex as $key => $val)
634 {
635 $str = preg_replace("#".$key."#i", $val, $str);
636 }
637
638 /*
639 * Makes PHP tags safe
640 *
641 * Note: XML tags are inadvertently replaced too:
642 *
643 * <?xml
644 *
645 * But it doesn't seem to pose a problem.
646 *
647 */
648 if ($is_image === TRUE)
649 {
650 // Images have a tendency to have the PHP short opening and closing tags every so often
651 // so we skip those and only do the long opening tags.
652 $str = str_replace(array('<?php', '<?PHP'), array('&lt;?php', '&lt;?PHP'), $str);
653 }
654 else
655 {
656 $str = str_replace(array('<?php', '<?PHP', '<?', '?'.'>'), array('&lt;?php', '&lt;?PHP', '&lt;?', '?&gt;'), $str);
657 }
658
659 /*
660 * Compact any exploded words
661 *
662 * This corrects words like: j a v a s c r i p t
663 * These words are compacted back to their correct state.
664 *
665 */
666 $words = array('javascript', 'expression', 'vbscript', 'script', 'applet', 'alert', 'document', 'write', 'cookie', 'window');
667 foreach ($words as $word)
668 {
669 $temp = '';
670
671 for ($i = 0, $wordlen = strlen($word); $i < $wordlen; $i++)
672 {
673 $temp .= substr($word, $i, 1)."\s*";
674 }
675
676 // We only want to do this when it is followed by a non-word character
677 // That way valid stuff like "dealer to" does not become "dealerto"
678 $str = preg_replace_callback('#('.substr($temp, 0, -3).')(\W)#is', array($this, '_compact_exploded_words'), $str);
679 }
680
681 /*
682 * Remove disallowed Javascript in links or img tags
683 * We used to do some version comparisons and use of stripos for PHP5, but it is dog slow compared
684 * to these simplified non-capturing preg_match(), especially if the pattern exists in the string
685 */
686 do
687 {
688 $original = $str;
689
690 if (preg_match("/<a/i", $str))
691 {
692 $str = preg_replace_callback("#<a\s+([^>]*?)(>|$)#si", array($this, '_js_link_removal'), $str);
693 }
694
695 if (preg_match("/<img/i", $str))
696 {
697 $str = preg_replace_callback("#<img\s+([^>]*?)(\s?/?>|$)#si", array($this, '_js_img_removal'), $str);
698 }
699
700 if (preg_match("/script/i", $str) OR preg_match("/xss/i", $str))
701 {
702 $str = preg_replace("#<(/*)(script|xss)(.*?)\>#si", '[removed]', $str);
703 }
704 }
705 while($original != $str);
706
707 unset($original);
708
709 /*
710 * Remove JavaScript Event Handlers
711 *
712 * Note: This code is a little blunt. It removes
713 * the event handler and anything up to the closing >,
714 * but it's unlikely to be a problem.
715 *
716 */
717 $event_handlers = array('[^a-z_\-]on\w*','xmlns');
718
719 if ($is_image === TRUE)
720 {
721 /*
722 * Adobe Photoshop puts XML metadata into JFIF images, including namespacing,
723 * so we have to allow this for images. -Paul
724 */
725 unset($event_handlers[array_search('xmlns', $event_handlers)]);
726 }
727
728 $str = preg_replace("#<([^><]+?)(".implode('|', $event_handlers).")(\s*=\s*[^><]*)([><]*)#i", "<\\1\\4", $str);
729
730 /*
731 * Sanitize naughty HTML elements
732 *
733 * If a tag containing any of the words in the list
734 * below is found, the tag gets converted to entities.
735 *
736 * So this: <blink>
737 * Becomes: &lt;blink&gt;
738 *
739 */
740 $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';
741 $str = preg_replace_callback('#<(/*\s*)('.$naughty.')([^><]*)([><]*)#is', array($this, '_sanitize_naughty_html'), $str);
742
743 /*
744 * Sanitize naughty scripting elements
745 *
746 * Similar to above, only instead of looking for
747 * tags it looks for PHP and JavaScript commands
748 * that are disallowed. Rather than removing the
749 * code, it simply converts the parenthesis to entities
750 * rendering the code un-executable.
751 *
752 * For example: eval('some code')
753 * Becomes: eval&#40;'some code'&#41;
754 *
755 */
756 $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);
757
758 /*
759 * Final clean up
760 *
761 * This adds a bit of extra precaution in case
762 * something got through the above filters
763 *
764 */
765 foreach ($this->never_allowed_str as $key => $val)
766 {
767 $str = str_replace($key, $val, $str);
768 }
769
770 foreach ($this->never_allowed_regex as $key => $val)
771 {
772 $str = preg_replace("#".$key."#i", $val, $str);
773 }
774
775 /*
776 * Images are Handled in a Special Way
777 * - Essentially, we want to know that after all of the character conversion is done whether
778 * any unwanted, likely XSS, code was found. If not, we return TRUE, as the image is clean.
779 * However, if the string post-conversion does not matched the string post-removal of XSS,
780 * then it fails, as there was unwanted XSS code found and removed/changed during processing.
781 */
782
783 if ($is_image === TRUE)
784 {
785 if ($str == $converted_string)
786 {
787 return TRUE;
788 }
789 else
790 {
791 return FALSE;
792 }
793 }
794
795 log_message('debug', "XSS Filtering completed");
796 return $str;
797 }
798
799 // --------------------------------------------------------------------
800
801 /**
802 * Random Hash for protecting URLs
803 *
804 * @access public
805 * @return string
806 */
807 function xss_hash()
808 {
809 if ($this->xss_hash == '')
810 {
811 if (phpversion() >= 4.2)
812 mt_srand();
813 else
814 mt_srand(hexdec(substr(md5(microtime()), -8)) & 0x7fffffff);
815
816 $this->xss_hash = md5(time() + mt_rand(0, 1999999999));
817 }
818
819 return $this->xss_hash;
820 }
821
822 // --------------------------------------------------------------------
823
824 /**
825 * Remove Invisible Characters
826 *
827 * This prevents sandwiching null characters
828 * between ascii characters, like Java\0script.
829 *
830 * @access public
831 * @param string
832 * @return string
833 */
834 function _remove_invisible_characters($str)
835 {
836 static $non_displayables;
837
838 if ( ! isset($non_displayables))
839 {
840 // every control character except newline (dec 10), carriage return (dec 13), and horizontal tab (dec 09),
841 $non_displayables = array(
842 '/%0[0-8bcef]/', // url encoded 00-08, 11, 12, 14, 15
843 '/%1[0-9a-f]/', // url encoded 16-31
844 '/[\x00-\x08]/', // 00-08
845 '/\x0b/', '/\x0c/', // 11, 12
846 '/[\x0e-\x1f]/' // 14-31
847 );
848 }
849
850 do
851 {
852 $cleaned = $str;
853 $str = preg_replace($non_displayables, '', $str);
854 }
855 while ($cleaned != $str);
856
857 return $str;
858 }
859
860 // --------------------------------------------------------------------
861
862 /**
863 * Compact Exploded Words
864 *
865 * Callback function for xss_clean() to remove whitespace from
866 * things like j a v a s c r i p t
867 *
868 * @access public
869 * @param type
870 * @return type
871 */
872 function _compact_exploded_words($matches)
873 {
874 return preg_replace('/\s+/s', '', $matches[1]).$matches[2];
875 }
876
877 // --------------------------------------------------------------------
878
879 /**
880 * Sanitize Naughty HTML
881 *
882 * Callback function for xss_clean() to remove naughty HTML elements
883 *
884 * @access private
885 * @param array
886 * @return string
887 */
888 function _sanitize_naughty_html($matches)
889 {
890 // encode opening brace
891 $str = '&lt;'.$matches[1].$matches[2].$matches[3];
892
893 // encode captured opening or closing brace to prevent recursive vectors
894 $str .= str_replace(array('>', '<'), array('&gt;', '&lt;'), $matches[4]);
895
896 return $str;
897 }
898
899 // --------------------------------------------------------------------
900
901 /**
902 * JS Link Removal
903 *
904 * Callback function for xss_clean() to sanitize links
905 * This limits the PCRE backtracks, making it more performance friendly
906 * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in
907 * PHP 5.2+ on link-heavy strings
908 *
909 * @access private
910 * @param array
911 * @return string
912 */
913 function _js_link_removal($match)
914 {
915 $attributes = $this->_filter_attributes(str_replace(array('<', '>'), '', $match[1]));
916 return str_replace($match[1], preg_replace("#href=.*?(alert\(|alert&\#40;|javascript\:|charset\=|window\.|document\.|\.cookie|<script|<xss|base64\s*,)#si", "", $attributes), $match[0]);
917 }
918
919 /**
920 * JS Image Removal
921 *
922 * Callback function for xss_clean() to sanitize image tags
923 * This limits the PCRE backtracks, making it more performance friendly
924 * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in
925 * PHP 5.2+ on image tag heavy strings
926 *
927 * @access private
928 * @param array
929 * @return string
930 */
931 function _js_img_removal($match)
932 {
933 $attributes = $this->_filter_attributes(str_replace(array('<', '>'), '', $match[1]));
934 return str_replace($match[1], preg_replace("#src=.*?(alert\(|alert&\#40;|javascript\:|charset\=|window\.|document\.|\.cookie|<script|<xss|base64\s*,)#si", "", $attributes), $match[0]);
935 }
936
937 // --------------------------------------------------------------------
938
939 /**
940 * Attribute Conversion
941 *
942 * Used as a callback for XSS Clean
943 *
944 * @access public
945 * @param array
946 * @return string
947 */
948 function _convert_attribute($match)
949 {
Derek Jones9959fed2009-02-04 20:37:40 +0000950 return str_replace(array('>', '<', '\\'), array('&gt;', '&lt;', '\\\\'), $match[0]);
Derek Allard2067d1a2008-11-13 22:59:24 +0000951 }
952
953 // --------------------------------------------------------------------
954
955 /**
956 * HTML Entity Decode Callback
957 *
958 * Used as a callback for XSS Clean
959 *
960 * @access public
961 * @param array
962 * @return string
963 */
964 function _html_entity_decode_callback($match)
965 {
966 $CFG =& load_class('Config');
967 $charset = $CFG->item('charset');
968
969 return $this->_html_entity_decode($match[0], strtoupper($charset));
970 }
971
972 // --------------------------------------------------------------------
973
974 /**
975 * HTML Entities Decode
976 *
977 * This function is a replacement for html_entity_decode()
978 *
979 * In some versions of PHP the native function does not work
980 * when UTF-8 is the specified character set, so this gives us
981 * a work-around. More info here:
982 * http://bugs.php.net/bug.php?id=25670
983 *
984 * @access private
985 * @param string
986 * @param string
987 * @return string
988 */
989 /* -------------------------------------------------
990 /* Replacement for html_entity_decode()
991 /* -------------------------------------------------*/
992
993 /*
994 NOTE: html_entity_decode() has a bug in some PHP versions when UTF-8 is the
995 character set, and the PHP developers said they were not back porting the
996 fix to versions other than PHP 5.x.
997 */
998 function _html_entity_decode($str, $charset='UTF-8')
999 {
1000 if (stristr($str, '&') === FALSE) return $str;
1001
1002 // The reason we are not using html_entity_decode() by itself is because
1003 // while it is not technically correct to leave out the semicolon
1004 // at the end of an entity most browsers will still interpret the entity
1005 // correctly. html_entity_decode() does not convert entities without
1006 // semicolons, so we are left with our own little solution here. Bummer.
1007
1008 if (function_exists('html_entity_decode') && (strtolower($charset) != 'utf-8' OR version_compare(phpversion(), '5.0.0', '>=')))
1009 {
1010 $str = html_entity_decode($str, ENT_COMPAT, $charset);
1011 $str = preg_replace('~&#x(0*[0-9a-f]{2,5})~ei', 'chr(hexdec("\\1"))', $str);
1012 return preg_replace('~&#([0-9]{2,4})~e', 'chr(\\1)', $str);
1013 }
1014
1015 // Numeric Entities
1016 $str = preg_replace('~&#x(0*[0-9a-f]{2,5});{0,1}~ei', 'chr(hexdec("\\1"))', $str);
1017 $str = preg_replace('~&#([0-9]{2,4});{0,1}~e', 'chr(\\1)', $str);
1018
1019 // Literal Entities - Slightly slow so we do another check
1020 if (stristr($str, '&') === FALSE)
1021 {
1022 $str = strtr($str, array_flip(get_html_translation_table(HTML_ENTITIES)));
1023 }
1024
1025 return $str;
1026 }
1027
1028 // --------------------------------------------------------------------
1029
1030 /**
1031 * Filter Attributes
1032 *
1033 * Filters tag attributes for consistency and safety
1034 *
1035 * @access public
1036 * @param string
1037 * @return string
1038 */
1039 function _filter_attributes($str)
1040 {
1041 $out = '';
1042
1043 if (preg_match_all('#\s*[a-z\-]+\s*=\s*(\042|\047)([^\\1]*?)\\1#is', $str, $matches))
1044 {
1045 foreach ($matches[0] as $match)
1046 {
Derek Jones9959fed2009-02-04 20:37:40 +00001047 $out .= preg_replace("#/\*.*?\*/#s", '', $match);
Derek Allard2067d1a2008-11-13 22:59:24 +00001048 }
1049 }
1050
1051 return $out;
1052 }
1053
1054 // --------------------------------------------------------------------
1055
1056}
1057// END Input class
1058
1059/* End of file Input.php */
Derek Jonesa3ffbbb2008-05-11 18:18:29 +00001060/* Location: ./system/libraries/Input.php */