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, 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*\(" => '[removed]', // CSS and IE
52 "Redirect\s+302" => '[removed]'
58 * Sets whether to globally enable the XSS processing
59 * and whether to allow the $_GET array
65 log_message('debug', "Input Class Initialized");
67 $CFG =& load_class('Config');
68 $this->use_xss_clean = ($CFG->item('global_xss_filtering') === TRUE) ? TRUE : FALSE;
69 $this->allow_get_array = ($CFG->item('enable_query_strings') === TRUE) ? TRUE : FALSE;
70 $this->_sanitize_globals();
73 // --------------------------------------------------------------------
78 * This function does the following:
80 * Unsets $_GET data (if query strings are not enabled)
82 * Unsets all globals if register_globals is enabled
84 * Standardizes newline characters to \n
89 function _sanitize_globals()
91 // Would kind of be "wrong" to unset any of these GLOBALS
92 $protected = array('_SERVER', '_GET', '_POST', '_FILES', '_REQUEST', '_SESSION', '_ENV', 'GLOBALS', 'HTTP_RAW_POST_DATA',
93 'system_folder', 'application_folder', 'BM', 'EXT', 'CFG', 'URI', 'RTR', 'OUT', 'IN');
95 // Unset globals for security.
96 // This is effectively the same as register_globals = off
97 foreach (array($_GET, $_POST, $_COOKIE, $_SERVER, $_FILES, $_ENV, (isset($_SESSION) && is_array($_SESSION)) ? $_SESSION : array()) as $global)
99 if ( ! is_array($global))
101 if ( ! in_array($global, $protected))
103 unset($GLOBALS[$global]);
108 foreach ($global as $key => $val)
110 if ( ! in_array($key, $protected))
112 unset($GLOBALS[$key]);
117 foreach($val as $k => $v)
119 if ( ! in_array($k, $protected))
129 // Is $_GET data allowed? If not we'll set the $_GET to an empty array
130 if ($this->allow_get_array == FALSE)
136 $_GET = $this->_clean_input_data($_GET);
140 $_POST = $this->_clean_input_data($_POST);
142 // Clean $_COOKIE Data
143 // Also get rid of specially treated cookies that might be set by a server
144 // or silly application, that are of no use to a CI application anyway
145 // but that when present will trip our 'Disallowed Key Characters' alarm
146 // http://www.ietf.org/rfc/rfc2109.txt
147 // note that the key names below are single quoted strings, and are not PHP variables
148 unset($_COOKIE['$Version']);
149 unset($_COOKIE['$Path']);
150 unset($_COOKIE['$Domain']);
151 $_COOKIE = $this->_clean_input_data($_COOKIE);
153 log_message('debug', "Global POST and COOKIE data sanitized");
156 // --------------------------------------------------------------------
161 * This is a helper function. It escapes data and
162 * standardizes newline characters to \n
168 function _clean_input_data($str)
172 $new_array = array();
173 foreach ($str as $key => $val)
175 $new_array[$this->_clean_input_keys($key)] = $this->_clean_input_data($val);
180 // We strip slashes if magic quotes is on to keep things consistent
181 if (get_magic_quotes_gpc())
183 $str = stripslashes($str);
186 // Should we filter the input data?
187 if ($this->use_xss_clean === TRUE)
189 $str = $this->xss_clean($str);
192 // Standardize newlines
193 if (strpos($str, "\r") !== FALSE)
195 $str = str_replace(array("\r\n", "\r"), "\n", $str);
201 // --------------------------------------------------------------------
206 * This is a helper function. To prevent malicious users
207 * from trying to exploit keys we make sure that keys are
208 * only named with alpha-numeric text and a few other items.
214 function _clean_input_keys($str)
216 if ( ! preg_match("/^[a-z0-9:_\/-]+$/i", $str))
218 exit('Disallowed Key Characters.');
224 // --------------------------------------------------------------------
229 * This is a helper function to retrieve values from global arrays
237 function _fetch_from_array(&$array, $index = '', $xss_clean = FALSE)
239 if ( ! isset($array[$index]))
244 if ($xss_clean === TRUE)
246 return $this->xss_clean($array[$index]);
249 return $array[$index];
252 // --------------------------------------------------------------------
255 * Fetch an item from the GET array
262 function get($index = '', $xss_clean = FALSE)
264 return $this->_fetch_from_array($_GET, $index, $xss_clean);
267 // --------------------------------------------------------------------
270 * Fetch an item from the POST array
277 function post($index = '', $xss_clean = FALSE)
279 return $this->_fetch_from_array($_POST, $index, $xss_clean);
282 // --------------------------------------------------------------------
285 * Fetch an item from either the GET array or the POST
288 * @param string The index key
289 * @param bool XSS cleaning
292 function get_post($index = '', $xss_clean = FALSE)
294 if ( ! isset($_POST[$index]) )
296 return $this->get($index, $xss_clean);
300 return $this->post($index, $xss_clean);
304 // --------------------------------------------------------------------
307 * Fetch an item from the COOKIE array
314 function cookie($index = '', $xss_clean = FALSE)
316 return $this->_fetch_from_array($_COOKIE, $index, $xss_clean);
319 // --------------------------------------------------------------------
322 * Fetch an item from the SERVER array
329 function server($index = '', $xss_clean = FALSE)
331 return $this->_fetch_from_array($_SERVER, $index, $xss_clean);
334 // --------------------------------------------------------------------
337 * Fetch the IP Address
342 function ip_address()
344 if ($this->ip_address !== FALSE)
346 return $this->ip_address;
349 if ($this->server('REMOTE_ADDR') AND $this->server('HTTP_CLIENT_IP'))
351 $this->ip_address = $_SERVER['HTTP_CLIENT_IP'];
353 elseif ($this->server('REMOTE_ADDR'))
355 $this->ip_address = $_SERVER['REMOTE_ADDR'];
357 elseif ($this->server('HTTP_CLIENT_IP'))
359 $this->ip_address = $_SERVER['HTTP_CLIENT_IP'];
361 elseif ($this->server('HTTP_X_FORWARDED_FOR'))
363 $this->ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
366 if ($this->ip_address === FALSE)
368 $this->ip_address = '0.0.0.0';
369 return $this->ip_address;
372 if (strstr($this->ip_address, ','))
374 $x = explode(',', $this->ip_address);
375 $this->ip_address = end($x);
378 if ( ! $this->valid_ip($this->ip_address))
380 $this->ip_address = '0.0.0.0';
383 return $this->ip_address;
386 // --------------------------------------------------------------------
389 * Validate IP Address
391 * Updated version suggested by Geert De Deckere
397 function valid_ip($ip)
399 $ip_segments = explode('.', $ip);
401 // Always 4 segments needed
402 if (count($ip_segments) != 4)
406 // IP can not start with 0
407 if ($ip_segments[0][0] == '0')
411 // Check each segment
412 foreach ($ip_segments as $segment)
414 // IP segments must be digits and can not be
415 // longer than 3 digits or greater then 255
416 if ($segment == '' OR preg_match("/[^0-9]/", $segment) OR $segment > 255 OR strlen($segment) > 3)
425 // --------------------------------------------------------------------
433 function user_agent()
435 if ($this->user_agent !== FALSE)
437 return $this->user_agent;
440 $this->user_agent = ( ! isset($_SERVER['HTTP_USER_AGENT'])) ? FALSE : $_SERVER['HTTP_USER_AGENT'];
442 return $this->user_agent;
445 // --------------------------------------------------------------------
454 function filename_security($str)
491 return stripslashes(str_replace($bad, '', $str));
494 // --------------------------------------------------------------------
499 * Sanitizes data so that Cross Site Scripting Hacks can be
500 * prevented. This function does a fair amount of work but
501 * it is extremely thorough, designed to prevent even the
502 * most obscure XSS attempts. Nothing is ever 100% foolproof,
503 * of course, but I haven't been able to get anything passed
506 * Note: This function should only be used to deal with data
507 * upon submission. It's not something that should
508 * be used for general runtime processing.
510 * This function was based in part on some code and ideas I
511 * got from Bitflux: http://blog.bitflux.ch/wiki/XSS_Prevention
513 * To help develop this script I used this great list of
514 * vulnerabilities along with a few other hacks I've
515 * harvested from examining vulnerabilities in other programs:
516 * http://ha.ckers.org/xss.html
522 function xss_clean($str, $is_image = FALSE)
525 * Is the string an array?
530 while (list($key) = each($str))
532 $str[$key] = $this->xss_clean($str[$key]);
539 * Remove Invisible Characters
541 $str = $this->_remove_invisible_characters($str);
544 * Protect GET variables in URLs
547 // 901119URL5918AMP18930PROTECT8198
549 $str = preg_replace('|\&([a-z\_0-9]+)\=([a-z\_0-9]+)|i', $this->xss_hash()."\\1=\\2", $str);
552 * Validate standard character entities
554 * Add a semicolon if missing. We do this to enable
555 * the conversion of entities to ASCII later.
558 $str = preg_replace('#(&\#?[0-9a-z]{2,})[\x00-\x20]*;?#i', "\\1;", $str);
561 * Validate UTF16 two byte encoding (x00)
563 * Just as above, adds a semicolon if missing.
566 $str = preg_replace('#(&\#x?)([0-9A-F]+);?#i',"\\1\\2;",$str);
569 * Un-Protect GET variables in URLs
571 $str = str_replace($this->xss_hash(), '&', $str);
576 * Just in case stuff like this is submitted:
578 * <a href="http://%77%77%77%2E%67%6F%6F%67%6C%65%2E%63%6F%6D">Google</a>
580 * Note: Use rawurldecode() so it does not remove plus signs
583 $str = rawurldecode($str);
586 * Convert character entities to ASCII
588 * This permits our tests below to work reliably.
589 * We only convert entities that are within tags since
590 * these are the ones that will pose security problems.
594 $str = preg_replace_callback("/[a-z]+=([\'\"]).*?\\1/si", array($this, '_convert_attribute'), $str);
596 $str = preg_replace_callback("/<\w+.*?(?=>|<|$)/si", array($this, '_html_entity_decode_callback'), $str);
599 * Remove Invisible Characters Again!
601 $str = $this->_remove_invisible_characters($str);
604 * Convert all tabs to spaces
606 * This prevents strings like this: ja vascript
607 * NOTE: we deal with spaces between characters later.
608 * NOTE: preg_replace was found to be amazingly slow here on large blocks of data,
609 * so we use str_replace.
613 if (strpos($str, "\t") !== FALSE)
615 $str = str_replace("\t", ' ', $str);
619 * Capture converted string for later comparison
621 $converted_string = $str;
624 * Not Allowed Under Any Conditions
627 foreach ($this->never_allowed_str as $key => $val)
629 $str = str_replace($key, $val, $str);
632 foreach ($this->never_allowed_regex as $key => $val)
634 $str = preg_replace("#".$key."#i", $val, $str);
638 * Makes PHP tags safe
640 * Note: XML tags are inadvertently replaced too:
644 * But it doesn't seem to pose a problem.
647 if ($is_image === TRUE)
649 // Images have a tendency to have the PHP short opening and closing tags every so often
650 // so we skip those and only do the long opening tags.
651 $str = str_replace(array('<?php', '<?PHP'), array('<?php', '<?PHP'), $str);
655 $str = str_replace(array('<?php', '<?PHP', '<?', '?'.'>'), array('<?php', '<?PHP', '<?', '?>'), $str);
659 * Compact any exploded words
661 * This corrects words like: j a v a s c r i p t
662 * These words are compacted back to their correct state.
665 $words = array('javascript', 'expression', 'vbscript', 'script', 'applet', 'alert', 'document', 'write', 'cookie', 'window');
666 foreach ($words as $word)
670 for ($i = 0, $wordlen = strlen($word); $i < $wordlen; $i++)
672 $temp .= substr($word, $i, 1)."\s*";
675 // We only want to do this when it is followed by a non-word character
676 // That way valid stuff like "dealer to" does not become "dealerto"
677 $str = preg_replace_callback('#('.substr($temp, 0, -3).')(\W)#is', array($this, '_compact_exploded_words'), $str);
681 * Remove disallowed Javascript in links or img tags
682 * We used to do some version comparisons and use of stripos for PHP5, but it is dog slow compared
683 * to these simplified non-capturing preg_match(), especially if the pattern exists in the string
689 if (preg_match("/<a/i", $str))
691 $str = preg_replace_callback("#<a\s+([^>]*?)(>|$)#si", array($this, '_js_link_removal'), $str);
694 if (preg_match("/<img/i", $str))
696 $str = preg_replace_callback("#<img\s+([^>]*?)(\s?/?>|$)#si", array($this, '_js_img_removal'), $str);
699 if (preg_match("/script/i", $str) OR preg_match("/xss/i", $str))
701 $str = preg_replace("#<(/*)(script|xss)(.*?)\>#si", '[removed]', $str);
704 while($original != $str);
709 * Remove JavaScript Event Handlers
711 * Note: This code is a little blunt. It removes
712 * the event handler and anything up to the closing >,
713 * but it's unlikely to be a problem.
716 $event_handlers = array('[^a-z_\-]on\w*','xmlns');
718 if ($is_image === TRUE)
721 * Adobe Photoshop puts XML metadata into JFIF images, including namespacing,
722 * so we have to allow this for images. -Paul
724 unset($event_handlers[array_search('xmlns', $event_handlers)]);
727 $str = preg_replace("#<([^><]+?)(".implode('|', $event_handlers).")(\s*=\s*[^><]*)([><]*)#i", "<\\1\\4", $str);
730 * Sanitize naughty HTML elements
732 * If a tag containing any of the words in the list
733 * below is found, the tag gets converted to entities.
736 * Becomes: <blink>
739 $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';
740 $str = preg_replace_callback('#<(/*\s*)('.$naughty.')([^><]*)([><]*)#is', array($this, '_sanitize_naughty_html'), $str);
743 * Sanitize naughty scripting elements
745 * Similar to above, only instead of looking for
746 * tags it looks for PHP and JavaScript commands
747 * that are disallowed. Rather than removing the
748 * code, it simply converts the parenthesis to entities
749 * rendering the code un-executable.
751 * For example: eval('some code')
752 * Becomes: eval('some code')
755 $str = preg_replace('#(alert|cmd|passthru|eval|exec|expression|system|fopen|fsockopen|file|file_get_contents|readfile|unlink)(\s*)\((.*?)\)#si', "\\1\\2(\\3)", $str);
760 * This adds a bit of extra precaution in case
761 * something got through the above filters
764 foreach ($this->never_allowed_str as $key => $val)
766 $str = str_replace($key, $val, $str);
769 foreach ($this->never_allowed_regex as $key => $val)
771 $str = preg_replace("#".$key."#i", $val, $str);
775 * Images are Handled in a Special Way
776 * - Essentially, we want to know that after all of the character conversion is done whether
777 * any unwanted, likely XSS, code was found. If not, we return TRUE, as the image is clean.
778 * However, if the string post-conversion does not matched the string post-removal of XSS,
779 * then it fails, as there was unwanted XSS code found and removed/changed during processing.
782 if ($is_image === TRUE)
784 if ($str == $converted_string)
794 log_message('debug', "XSS Filtering completed");
798 // --------------------------------------------------------------------
801 * Random Hash for protecting URLs
808 if ($this->xss_hash == '')
810 if (phpversion() >= 4.2)
813 mt_srand(hexdec(substr(md5(microtime()), -8)) & 0x7fffffff);
815 $this->xss_hash = md5(time() + mt_rand(0, 1999999999));
818 return $this->xss_hash;
821 // --------------------------------------------------------------------
824 * Remove Invisible Characters
826 * This prevents sandwiching null characters
827 * between ascii characters, like Java\0script.
833 function _remove_invisible_characters($str)
835 static $non_displayables;
837 if ( ! isset($non_displayables))
839 // every control character except newline (dec 10), carriage return (dec 13), and horizontal tab (dec 09),
840 $non_displayables = array(
841 '/%0[0-8bcef]/', // url encoded 00-08, 11, 12, 14, 15
842 '/%1[0-9a-f]/', // url encoded 16-31
843 '/[\x00-\x08]/', // 00-08
844 '/\x0b/', '/\x0c/', // 11, 12
845 '/[\x0e-\x1f]/' // 14-31
852 $str = preg_replace($non_displayables, '', $str);
854 while ($cleaned != $str);
859 // --------------------------------------------------------------------
862 * Compact Exploded Words
864 * Callback function for xss_clean() to remove whitespace from
865 * things like j a v a s c r i p t
871 function _compact_exploded_words($matches)
873 return preg_replace('/\s+/s', '', $matches[1]).$matches[2];
876 // --------------------------------------------------------------------
879 * Sanitize Naughty HTML
881 * Callback function for xss_clean() to remove naughty HTML elements
887 function _sanitize_naughty_html($matches)
889 // encode opening brace
890 $str = '<'.$matches[1].$matches[2].$matches[3];
892 // encode captured opening or closing brace to prevent recursive vectors
893 $str .= str_replace(array('>', '<'), array('>', '<'), $matches[4]);
898 // --------------------------------------------------------------------
903 * Callback function for xss_clean() to sanitize links
904 * This limits the PCRE backtracks, making it more performance friendly
905 * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in
906 * PHP 5.2+ on link-heavy strings
912 function _js_link_removal($match)
914 $attributes = $this->_filter_attributes(str_replace(array('<', '>'), '', $match[1]));
915 return str_replace($match[1], preg_replace("#href=.*?(alert\(|alert&\#40;|javascript\:|charset\=|window\.|document\.|\.cookie|<script|<xss|base64\s*,)#si", "", $attributes), $match[0]);
921 * Callback function for xss_clean() to sanitize image tags
922 * This limits the PCRE backtracks, making it more performance friendly
923 * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in
924 * PHP 5.2+ on image tag heavy strings
930 function _js_img_removal($match)
932 $attributes = $this->_filter_attributes(str_replace(array('<', '>'), '', $match[1]));
933 return str_replace($match[1], preg_replace("#src=.*?(alert\(|alert&\#40;|javascript\:|charset\=|window\.|document\.|\.cookie|<script|<xss|base64\s*,)#si", "", $attributes), $match[0]);
936 // --------------------------------------------------------------------
939 * Attribute Conversion
941 * Used as a callback for XSS Clean
947 function _convert_attribute($match)
949 return str_replace(array('>', '<'), array('>', '<'), $match[0]);
952 // --------------------------------------------------------------------
955 * HTML Entity Decode Callback
957 * Used as a callback for XSS Clean
963 function _html_entity_decode_callback($match)
965 $CFG =& load_class('Config');
966 $charset = $CFG->item('charset');
968 return $this->_html_entity_decode($match[0], strtoupper($charset));
971 // --------------------------------------------------------------------
974 * HTML Entities Decode
976 * This function is a replacement for html_entity_decode()
978 * In some versions of PHP the native function does not work
979 * when UTF-8 is the specified character set, so this gives us
980 * a work-around. More info here:
981 * http://bugs.php.net/bug.php?id=25670
988 /* -------------------------------------------------
989 /* Replacement for html_entity_decode()
990 /* -------------------------------------------------*/
993 NOTE: html_entity_decode() has a bug in some PHP versions when UTF-8 is the
994 character set, and the PHP developers said they were not back porting the
995 fix to versions other than PHP 5.x.
997 function _html_entity_decode($str, $charset='UTF-8')
999 if (stristr($str, '&') === FALSE) return $str;
1001 // The reason we are not using html_entity_decode() by itself is because
1002 // while it is not technically correct to leave out the semicolon
1003 // at the end of an entity most browsers will still interpret the entity
1004 // correctly. html_entity_decode() does not convert entities without
1005 // semicolons, so we are left with our own little solution here. Bummer.
1007 if (function_exists('html_entity_decode') && (strtolower($charset) != 'utf-8' OR version_compare(phpversion(), '5.0.0', '>=')))
1009 $str = html_entity_decode($str, ENT_COMPAT, $charset);
1010 $str = preg_replace('~&#x(0*[0-9a-f]{2,5})~ei', 'chr(hexdec("\\1"))', $str);
1011 return preg_replace('~&#([0-9]{2,4})~e', 'chr(\\1)', $str);
1015 $str = preg_replace('~&#x(0*[0-9a-f]{2,5});{0,1}~ei', 'chr(hexdec("\\1"))', $str);
1016 $str = preg_replace('~&#([0-9]{2,4});{0,1}~e', 'chr(\\1)', $str);
1018 // Literal Entities - Slightly slow so we do another check
1019 if (stristr($str, '&') === FALSE)
1021 $str = strtr($str, array_flip(get_html_translation_table(HTML_ENTITIES)));
1027 // --------------------------------------------------------------------
1032 * Filters tag attributes for consistency and safety
1038 function _filter_attributes($str)
1042 if (preg_match_all('#\s*[a-z\-]+\s*=\s*(\042|\047)([^\\1]*?)\\1#is', $str, $matches))
1044 foreach ($matches[0] as $match)
1053 // --------------------------------------------------------------------
1058 /* End of file Input.php */
1059 /* Location: ./system/libraries/Input.php */