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