1 <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
5 * An open source application development framework for PHP 4.3.2 or newer
8 * @author ExpressionEngine Dev Team
9 * @copyright Copyright (c) 2008 - 2009, EllisLab, Inc.
10 * @license http://codeigniter.com/user_guide/license.html
11 * @link http://codeigniter.com
16 // ------------------------------------------------------------------------
21 * Pre-processes global input data for security
23 * @package CodeIgniter
24 * @subpackage Libraries
26 * @author ExpressionEngine Dev Team
27 * @link http://codeigniter.com/user_guide/libraries/input.html
30 var $use_xss_clean = FALSE;
32 var $ip_address = FALSE;
33 var $user_agent = FALSE;
34 var $allow_get_array = FALSE;
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]',
46 '<![CDATA[' => '<![CDATA['
48 /* never allowed, regex replacement */
49 var $never_allowed_regex = array(
50 "javascript\s*:" => '[removed]',
51 "expression\s*(\(|&\#40;)" => '[removed]', // CSS and IE
52 "vbscript\s*:" => '[removed]', // IE, surprise!
53 "Redirect\s+302" => '[removed]'
59 * Sets whether to globally enable the XSS processing
60 * and whether to allow the $_GET array
66 log_message('debug', "Input Class Initialized");
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();
74 // --------------------------------------------------------------------
79 * This function does the following:
81 * Unsets $_GET data (if query strings are not enabled)
83 * Unsets all globals if register_globals is enabled
85 * Standardizes newline characters to \n
90 function _sanitize_globals()
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');
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)
100 if ( ! is_array($global))
102 if ( ! in_array($global, $protected))
104 unset($GLOBALS[$global]);
109 foreach ($global as $key => $val)
111 if ( ! in_array($key, $protected))
113 unset($GLOBALS[$key]);
118 foreach($val as $k => $v)
120 if ( ! in_array($k, $protected))
130 // Is $_GET data allowed? If not we'll set the $_GET to an empty array
131 if ($this->allow_get_array == FALSE)
137 $_GET = $this->_clean_input_data($_GET);
141 $_POST = $this->_clean_input_data($_POST);
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);
154 log_message('debug', "Global POST and COOKIE data sanitized");
157 // --------------------------------------------------------------------
162 * This is a helper function. It escapes data and
163 * standardizes newline characters to \n
169 function _clean_input_data($str)
173 $new_array = array();
174 foreach ($str as $key => $val)
176 $new_array[$this->_clean_input_keys($key)] = $this->_clean_input_data($val);
181 // We strip slashes if magic quotes is on to keep things consistent
182 if (get_magic_quotes_gpc())
184 $str = stripslashes($str);
187 // Should we filter the input data?
188 if ($this->use_xss_clean === TRUE)
190 $str = $this->xss_clean($str);
193 // Standardize newlines
194 if (strpos($str, "\r") !== FALSE)
196 $str = str_replace(array("\r\n", "\r"), "\n", $str);
202 // --------------------------------------------------------------------
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.
215 function _clean_input_keys($str)
217 if ( ! preg_match("/^[a-z0-9:_\/-]+$/i", $str))
219 exit('Disallowed Key Characters.');
225 // --------------------------------------------------------------------
230 * This is a helper function to retrieve values from global arrays
238 function _fetch_from_array(&$array, $index = '', $xss_clean = FALSE)
240 if ( ! isset($array[$index]))
245 if ($xss_clean === TRUE)
247 return $this->xss_clean($array[$index]);
250 return $array[$index];
253 // --------------------------------------------------------------------
256 * Fetch an item from the GET array
263 function get($index = '', $xss_clean = FALSE)
265 return $this->_fetch_from_array($_GET, $index, $xss_clean);
268 // --------------------------------------------------------------------
271 * Fetch an item from the POST array
278 function post($index = '', $xss_clean = FALSE)
280 return $this->_fetch_from_array($_POST, $index, $xss_clean);
283 // --------------------------------------------------------------------
286 * Fetch an item from either the GET array or the POST
289 * @param string The index key
290 * @param bool XSS cleaning
293 function get_post($index = '', $xss_clean = FALSE)
295 if ( ! isset($_POST[$index]) )
297 return $this->get($index, $xss_clean);
301 return $this->post($index, $xss_clean);
305 // --------------------------------------------------------------------
308 * Fetch an item from the COOKIE array
315 function cookie($index = '', $xss_clean = FALSE)
317 return $this->_fetch_from_array($_COOKIE, $index, $xss_clean);
320 // --------------------------------------------------------------------
323 * Fetch an item from the SERVER array
330 function server($index = '', $xss_clean = FALSE)
332 return $this->_fetch_from_array($_SERVER, $index, $xss_clean);
335 // --------------------------------------------------------------------
338 * Fetch the IP Address
343 function ip_address()
345 if ($this->ip_address !== FALSE)
347 return $this->ip_address;
350 if (config_item('proxy_ips') != '' && $this->server('HTTP_X_FORWARDED_FOR') && $this->server('REMOTE_ADDR'))
352 $proxies = preg_split('/[\s,]/', config_item('proxy_ips'), -1, PREG_SPLIT_NO_EMPTY);
353 $proxies = is_array($proxies) ? $proxies : array($proxies);
355 $this->ip_address = in_array($_SERVER['REMOTE_ADDR'], $proxies) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];
357 elseif ($this->server('REMOTE_ADDR') AND $this->server('HTTP_CLIENT_IP'))
359 $this->ip_address = $_SERVER['HTTP_CLIENT_IP'];
361 elseif ($this->server('REMOTE_ADDR'))
363 $this->ip_address = $_SERVER['REMOTE_ADDR'];
365 elseif ($this->server('HTTP_CLIENT_IP'))
367 $this->ip_address = $_SERVER['HTTP_CLIENT_IP'];
369 elseif ($this->server('HTTP_X_FORWARDED_FOR'))
371 $this->ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
374 if ($this->ip_address === FALSE)
376 $this->ip_address = '0.0.0.0';
377 return $this->ip_address;
380 if (strstr($this->ip_address, ','))
382 $x = explode(',', $this->ip_address);
383 $this->ip_address = trim(end($x));
386 if ( ! $this->valid_ip($this->ip_address))
388 $this->ip_address = '0.0.0.0';
391 return $this->ip_address;
394 // --------------------------------------------------------------------
397 * Validate IP Address
399 * Updated version suggested by Geert De Deckere
405 function valid_ip($ip)
407 $ip_segments = explode('.', $ip);
409 // Always 4 segments needed
410 if (count($ip_segments) != 4)
414 // IP can not start with 0
415 if ($ip_segments[0][0] == '0')
419 // Check each segment
420 foreach ($ip_segments as $segment)
422 // IP segments must be digits and can not be
423 // longer than 3 digits or greater then 255
424 if ($segment == '' OR preg_match("/[^0-9]/", $segment) OR $segment > 255 OR strlen($segment) > 3)
433 // --------------------------------------------------------------------
441 function user_agent()
443 if ($this->user_agent !== FALSE)
445 return $this->user_agent;
448 $this->user_agent = ( ! isset($_SERVER['HTTP_USER_AGENT'])) ? FALSE : $_SERVER['HTTP_USER_AGENT'];
450 return $this->user_agent;
453 // --------------------------------------------------------------------
462 function filename_security($str)
499 return stripslashes(str_replace($bad, '', $str));
502 // --------------------------------------------------------------------
507 * Sanitizes data so that Cross Site Scripting Hacks can be
508 * prevented. This function does a fair amount of work but
509 * it is extremely thorough, designed to prevent even the
510 * most obscure XSS attempts. Nothing is ever 100% foolproof,
511 * of course, but I haven't been able to get anything passed
514 * Note: This function should only be used to deal with data
515 * upon submission. It's not something that should
516 * be used for general runtime processing.
518 * This function was based in part on some code and ideas I
519 * got from Bitflux: http://blog.bitflux.ch/wiki/XSS_Prevention
521 * To help develop this script I used this great list of
522 * vulnerabilities along with a few other hacks I've
523 * harvested from examining vulnerabilities in other programs:
524 * http://ha.ckers.org/xss.html
530 function xss_clean($str, $is_image = FALSE)
533 * Is the string an array?
538 while (list($key) = each($str))
540 $str[$key] = $this->xss_clean($str[$key]);
547 * Remove Invisible Characters
549 $str = $this->_remove_invisible_characters($str);
552 * Protect GET variables in URLs
555 // 901119URL5918AMP18930PROTECT8198
557 $str = preg_replace('|\&([a-z\_0-9]+)\=([a-z\_0-9]+)|i', $this->xss_hash()."\\1=\\2", $str);
560 * Validate standard character entities
562 * Add a semicolon if missing. We do this to enable
563 * the conversion of entities to ASCII later.
566 $str = preg_replace('#(&\#?[0-9a-z]{2,})([\x00-\x20])*;?#i', "\\1;\\2", $str);
569 * Validate UTF16 two byte encoding (x00)
571 * Just as above, adds a semicolon if missing.
574 $str = preg_replace('#(&\#x?)([0-9A-F]+);?#i',"\\1\\2;",$str);
577 * Un-Protect GET variables in URLs
579 $str = str_replace($this->xss_hash(), '&', $str);
584 * Just in case stuff like this is submitted:
586 * <a href="http://%77%77%77%2E%67%6F%6F%67%6C%65%2E%63%6F%6D">Google</a>
588 * Note: Use rawurldecode() so it does not remove plus signs
591 $str = rawurldecode($str);
594 * Convert character entities to ASCII
596 * This permits our tests below to work reliably.
597 * We only convert entities that are within tags since
598 * these are the ones that will pose security problems.
602 $str = preg_replace_callback("/[a-z]+=([\'\"]).*?\\1/si", array($this, '_convert_attribute'), $str);
604 $str = preg_replace_callback("/<\w+.*?(?=>|<|$)/si", array($this, '_html_entity_decode_callback'), $str);
607 * Remove Invisible Characters Again!
609 $str = $this->_remove_invisible_characters($str);
612 * Convert all tabs to spaces
614 * This prevents strings like this: ja vascript
615 * NOTE: we deal with spaces between characters later.
616 * NOTE: preg_replace was found to be amazingly slow here on large blocks of data,
617 * so we use str_replace.
621 if (strpos($str, "\t") !== FALSE)
623 $str = str_replace("\t", ' ', $str);
627 * Capture converted string for later comparison
629 $converted_string = $str;
632 * Not Allowed Under Any Conditions
635 foreach ($this->never_allowed_str as $key => $val)
637 $str = str_replace($key, $val, $str);
640 foreach ($this->never_allowed_regex as $key => $val)
642 $str = preg_replace("#".$key."#i", $val, $str);
646 * Makes PHP tags safe
648 * Note: XML tags are inadvertently replaced too:
652 * But it doesn't seem to pose a problem.
655 if ($is_image === TRUE)
657 // Images have a tendency to have the PHP short opening and closing tags every so often
658 // so we skip those and only do the long opening tags.
659 $str = preg_replace('/<\?(php)/i', "<?\\1", $str);
663 $str = str_replace(array('<?', '?'.'>'), array('<?', '?>'), $str);
667 * Compact any exploded words
669 * This corrects words like: j a v a s c r i p t
670 * These words are compacted back to their correct state.
673 $words = array('javascript', 'expression', 'vbscript', 'script', 'applet', 'alert', 'document', 'write', 'cookie', 'window');
674 foreach ($words as $word)
678 for ($i = 0, $wordlen = strlen($word); $i < $wordlen; $i++)
680 $temp .= substr($word, $i, 1)."\s*";
683 // We only want to do this when it is followed by a non-word character
684 // That way valid stuff like "dealer to" does not become "dealerto"
685 $str = preg_replace_callback('#('.substr($temp, 0, -3).')(\W)#is', array($this, '_compact_exploded_words'), $str);
689 * Remove disallowed Javascript in links or img tags
690 * We used to do some version comparisons and use of stripos for PHP5, but it is dog slow compared
691 * to these simplified non-capturing preg_match(), especially if the pattern exists in the string
697 if (preg_match("/<a/i", $str))
699 $str = preg_replace_callback("#<a\s+([^>]*?)(>|$)#si", array($this, '_js_link_removal'), $str);
702 if (preg_match("/<img/i", $str))
704 $str = preg_replace_callback("#<img\s+([^>]*?)(\s?/?>|$)#si", array($this, '_js_img_removal'), $str);
707 if (preg_match("/script/i", $str) OR preg_match("/xss/i", $str))
709 $str = preg_replace("#<(/*)(script|xss)(.*?)\>#si", '[removed]', $str);
712 while($original != $str);
717 * Remove JavaScript Event Handlers
719 * Note: This code is a little blunt. It removes
720 * the event handler and anything up to the closing >,
721 * but it's unlikely to be a problem.
724 $event_handlers = array('[^a-z_\-]on\w*','xmlns');
726 if ($is_image === TRUE)
729 * Adobe Photoshop puts XML metadata into JFIF images, including namespacing,
730 * so we have to allow this for images. -Paul
732 unset($event_handlers[array_search('xmlns', $event_handlers)]);
735 $str = preg_replace("#<([^><]+?)(".implode('|', $event_handlers).")(\s*=\s*[^><]*)([><]*)#i", "<\\1\\4", $str);
738 * Sanitize naughty HTML elements
740 * If a tag containing any of the words in the list
741 * below is found, the tag gets converted to entities.
744 * Becomes: <blink>
747 $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';
748 $str = preg_replace_callback('#<(/*\s*)('.$naughty.')([^><]*)([><]*)#is', array($this, '_sanitize_naughty_html'), $str);
751 * Sanitize naughty scripting elements
753 * Similar to above, only instead of looking for
754 * tags it looks for PHP and JavaScript commands
755 * that are disallowed. Rather than removing the
756 * code, it simply converts the parenthesis to entities
757 * rendering the code un-executable.
759 * For example: eval('some code')
760 * Becomes: eval('some code')
763 $str = preg_replace('#(alert|cmd|passthru|eval|exec|expression|system|fopen|fsockopen|file|file_get_contents|readfile|unlink)(\s*)\((.*?)\)#si', "\\1\\2(\\3)", $str);
768 * This adds a bit of extra precaution in case
769 * something got through the above filters
772 foreach ($this->never_allowed_str as $key => $val)
774 $str = str_replace($key, $val, $str);
777 foreach ($this->never_allowed_regex as $key => $val)
779 $str = preg_replace("#".$key."#i", $val, $str);
783 * Images are Handled in a Special Way
784 * - Essentially, we want to know that after all of the character conversion is done whether
785 * any unwanted, likely XSS, code was found. If not, we return TRUE, as the image is clean.
786 * However, if the string post-conversion does not matched the string post-removal of XSS,
787 * then it fails, as there was unwanted XSS code found and removed/changed during processing.
790 if ($is_image === TRUE)
792 if ($str == $converted_string)
802 log_message('debug', "XSS Filtering completed");
806 // --------------------------------------------------------------------
809 * Random Hash for protecting URLs
816 if ($this->xss_hash == '')
818 if (phpversion() >= 4.2)
821 mt_srand(hexdec(substr(md5(microtime()), -8)) & 0x7fffffff);
823 $this->xss_hash = md5(time() + mt_rand(0, 1999999999));
826 return $this->xss_hash;
829 // --------------------------------------------------------------------
832 * Remove Invisible Characters
834 * This prevents sandwiching null characters
835 * between ascii characters, like Java\0script.
841 function _remove_invisible_characters($str)
843 static $non_displayables;
845 if ( ! isset($non_displayables))
847 // every control character except newline (dec 10), carriage return (dec 13), and horizontal tab (dec 09),
848 $non_displayables = array(
849 '/%0[0-8bcef]/', // url encoded 00-08, 11, 12, 14, 15
850 '/%1[0-9a-f]/', // url encoded 16-31
851 '/[\x00-\x08]/', // 00-08
852 '/\x0b/', '/\x0c/', // 11, 12
853 '/[\x0e-\x1f]/' // 14-31
860 $str = preg_replace($non_displayables, '', $str);
862 while ($cleaned != $str);
867 // --------------------------------------------------------------------
870 * Compact Exploded Words
872 * Callback function for xss_clean() to remove whitespace from
873 * things like j a v a s c r i p t
879 function _compact_exploded_words($matches)
881 return preg_replace('/\s+/s', '', $matches[1]).$matches[2];
884 // --------------------------------------------------------------------
887 * Sanitize Naughty HTML
889 * Callback function for xss_clean() to remove naughty HTML elements
895 function _sanitize_naughty_html($matches)
897 // encode opening brace
898 $str = '<'.$matches[1].$matches[2].$matches[3];
900 // encode captured opening or closing brace to prevent recursive vectors
901 $str .= str_replace(array('>', '<'), array('>', '<'), $matches[4]);
906 // --------------------------------------------------------------------
911 * Callback function for xss_clean() to sanitize links
912 * This limits the PCRE backtracks, making it more performance friendly
913 * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in
914 * PHP 5.2+ on link-heavy strings
920 function _js_link_removal($match)
922 $attributes = $this->_filter_attributes(str_replace(array('<', '>'), '', $match[1]));
923 return str_replace($match[1], preg_replace("#href=.*?(alert\(|alert&\#40;|javascript\:|charset\=|window\.|document\.|\.cookie|<script|<xss|base64\s*,)#si", "", $attributes), $match[0]);
929 * Callback function for xss_clean() to sanitize image tags
930 * This limits the PCRE backtracks, making it more performance friendly
931 * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in
932 * PHP 5.2+ on image tag heavy strings
938 function _js_img_removal($match)
940 $attributes = $this->_filter_attributes(str_replace(array('<', '>'), '', $match[1]));
941 return str_replace($match[1], preg_replace("#src=.*?(alert\(|alert&\#40;|javascript\:|charset\=|window\.|document\.|\.cookie|<script|<xss|base64\s*,)#si", "", $attributes), $match[0]);
944 // --------------------------------------------------------------------
947 * Attribute Conversion
949 * Used as a callback for XSS Clean
955 function _convert_attribute($match)
957 return str_replace(array('>', '<', '\\'), array('>', '<', '\\\\'), $match[0]);
960 // --------------------------------------------------------------------
963 * HTML Entity Decode Callback
965 * Used as a callback for XSS Clean
971 function _html_entity_decode_callback($match)
973 $CFG =& load_class('Config');
974 $charset = $CFG->item('charset');
976 return $this->_html_entity_decode($match[0], strtoupper($charset));
979 // --------------------------------------------------------------------
982 * HTML Entities Decode
984 * This function is a replacement for html_entity_decode()
986 * In some versions of PHP the native function does not work
987 * when UTF-8 is the specified character set, so this gives us
988 * a work-around. More info here:
989 * http://bugs.php.net/bug.php?id=25670
996 /* -------------------------------------------------
997 /* Replacement for html_entity_decode()
998 /* -------------------------------------------------*/
1001 NOTE: html_entity_decode() has a bug in some PHP versions when UTF-8 is the
1002 character set, and the PHP developers said they were not back porting the
1003 fix to versions other than PHP 5.x.
1005 function _html_entity_decode($str, $charset='UTF-8')
1007 if (stristr($str, '&') === FALSE) return $str;
1009 // The reason we are not using html_entity_decode() by itself is because
1010 // while it is not technically correct to leave out the semicolon
1011 // at the end of an entity most browsers will still interpret the entity
1012 // correctly. html_entity_decode() does not convert entities without
1013 // semicolons, so we are left with our own little solution here. Bummer.
1015 if (function_exists('html_entity_decode') && (strtolower($charset) != 'utf-8' OR version_compare(phpversion(), '5.0.0', '>=')))
1017 $str = html_entity_decode($str, ENT_COMPAT, $charset);
1018 $str = preg_replace('~&#x(0*[0-9a-f]{2,5})~ei', 'chr(hexdec("\\1"))', $str);
1019 return preg_replace('~&#([0-9]{2,4})~e', 'chr(\\1)', $str);
1023 $str = preg_replace('~&#x(0*[0-9a-f]{2,5});{0,1}~ei', 'chr(hexdec("\\1"))', $str);
1024 $str = preg_replace('~&#([0-9]{2,4});{0,1}~e', 'chr(\\1)', $str);
1026 // Literal Entities - Slightly slow so we do another check
1027 if (stristr($str, '&') === FALSE)
1029 $str = strtr($str, array_flip(get_html_translation_table(HTML_ENTITIES)));
1035 // --------------------------------------------------------------------
1040 * Filters tag attributes for consistency and safety
1046 function _filter_attributes($str)
1050 if (preg_match_all('#\s*[a-z\-]+\s*=\s*(\042|\047)([^\\1]*?)\\1#is', $str, $matches))
1052 foreach ($matches[0] as $match)
1054 $out .= preg_replace("#/\*.*?\*/#s", '', $match);
1061 // --------------------------------------------------------------------
1066 /* End of file Input.php */
1067 /* Location: ./system/libraries/Input.php */