blob: ad7b0c5718b15be413218e896714b2a57e2a6ee6 [file] [log] [blame]
adminb0dd10f2006-08-25 17:25:49 +00001<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
2/**
3 * Code Igniter
4 *
5 * An open source application development framework for PHP 4.3.2 or newer
6 *
7 * @package CodeIgniter
8 * @author Rick Ellis
9 * @copyright Copyright (c) 2006, pMachine, Inc.
10 * @license http://www.codeignitor.com/user_guide/license.html
11 * @link http://www.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 Rick Ellis
27 * @link http://www.codeigniter.com/user_guide/libraries/input.html
28 */
29class CI_Input {
30 var $use_xss_clean = FALSE;
31 var $ip_address = FALSE;
32 var $user_agent = FALSE;
33 var $allow_get_array = FALSE;
34
35 /**
36 * Constructor
37 *
38 * Sets whether to globally enable the XSS processing
39 * and whether to allow the $_GET array
40 *
41 * @access public
42 */
43 function CI_Input()
44 {
admin33de9a12006-09-28 06:50:16 +000045 $CFG =& _load_class('Config');
adminb0dd10f2006-08-25 17:25:49 +000046 $this->use_xss_clean = ($CFG->item('global_xss_filtering') === TRUE) ? TRUE : FALSE;
47 $this->allow_get_array = ($CFG->item('enable_query_strings') === TRUE) ? TRUE : FALSE;
48
49 log_message('debug', "Input Class Initialized");
50 $this->_sanitize_globals();
51 }
52 // END CI_Input()
53
54 // --------------------------------------------------------------------
55
56 /**
57 * Sanitize Globals
58 *
59 * This function does the folowing:
60 *
61 * Unsets $_GET data (if query strings are not enabled)
62 *
63 * Unsets all globals if register_globals is enabled
64 *
65 * Standardizes newline characters to \n
66 *
67 * @access private
68 * @return void
69 */
70 function _sanitize_globals()
71 {
72 // Unset globals. This is effectively the same as register_globals = off
73 foreach (array($_GET, $_POST, $_COOKIE) as $global)
74 {
75 if ( ! is_array($global))
76 {
77 unset($$global);
78 }
79 else
80 {
81 foreach ($global as $key => $val)
82 {
83 unset($$key);
84 }
85 }
86 }
87
88 // Is $_GET data allowed?
89 if ($this->allow_get_array == FALSE)
90 {
91 $_GET = array();
92 }
93
94 // Clean $_POST Data
95 if (is_array($_POST) AND count($_POST) > 0)
96 {
97 foreach($_POST as $key => $val)
98 {
99 if (is_array($val))
100 {
101 foreach($val as $k => $v)
102 {
103 $_POST[$this->_clean_input_keys($key)][$this->_clean_input_keys($k)] = $this->_clean_input_data($v);
104 }
105 }
106 else
107 {
108 $_POST[$this->_clean_input_keys($key)] = $this->_clean_input_data($val);
109 }
110 }
111 }
112
113 // Clean $_COOKIE Data
114 if (is_array($_COOKIE) AND count($_COOKIE) > 0)
115 {
116 foreach($_COOKIE as $key => $val)
117 {
118 $_COOKIE[$this->_clean_input_keys($key)] = $this->_clean_input_data($val);
119 }
120 }
121
122 log_message('debug', "Global POST and COOKIE data sanitized");
123 }
124 // END _sanitize_globals()
125
126 // --------------------------------------------------------------------
127
128 /**
129 * Clean Intput Data
130 *
131 * This is a helper function. It escapes data and
132 * standardizes newline characters to \n
133 *
134 * @access private
135 * @param string
136 * @return string
137 */
138 function _clean_input_data($str)
139 {
140 if (is_array($str))
141 {
142 $new_array = array();
143 foreach ($str as $key => $val)
144 {
145 $new_array[$key] = $this->_clean_input_data($val);
146 }
147 return $new_array;
148 }
149
150 if ($this->use_xss_clean === TRUE)
151 {
152 $str = $this->xss_clean($str);
153 }
154
155 return preg_replace("/\015\012|\015|\012/", "\n", $str);
156 }
157 // END _clean_input_data()
158
159 // --------------------------------------------------------------------
160
161 /**
162 * Clean Keys
163 *
164 * This is a helper function. To prevent malicious users
165 * from trying to exploit keys we make sure that keys are
166 * only named with alpha-numeric text and a few other items.
167 *
168 * @access private
169 * @param string
170 * @return string
171 */
172 function _clean_input_keys($str)
173 {
174 if ( ! preg_match("/^[a-z0-9:_\/-]+$/i", $str))
175 {
176 exit('Disallowed Key Characters: '.$str);
177 }
178
179 if ( ! get_magic_quotes_gpc())
180 {
181 return addslashes($str);
182 }
183
184 return $str;
185 }
186 // END _clean_input_keys()
187
188 // --------------------------------------------------------------------
189
190 /**
191 * Fetch an item from the POST array
192 *
193 * @access public
194 * @param string
195 * @return string
196 */
197 function post($index = '', $xss_clean = FALSE)
198 {
199 if ( ! isset($_POST[$index]))
200 {
201 return FALSE;
202 }
203 else
204 {
205 if ($xss_clean === TRUE)
206 {
207 return $this->xss_clean($_POST[$index]);
208 }
209 else
210 {
211 return $_POST[$index];
212 }
213 }
214 }
215 // END post()
216
217 // --------------------------------------------------------------------
218
219 /**
220 * Fetch an item from the COOKIE array
221 *
222 * @access public
223 * @param string
224 * @return string
225 */
226 function cookie($index = '', $xss_clean = FALSE)
227 {
228 if ( ! isset($_COOKIE[$index]))
229 {
230 return FALSE;
231 }
232 else
233 {
234 if ($xss_clean === TRUE)
235 {
236 return $this->xss_clean($_COOKIE[$index]);
237 }
238 else
239 {
240 return $_COOKIE[$index];
241 }
242 }
243 }
244 // END cookie()
245
246 // --------------------------------------------------------------------
247
248 /**
249 * Fetch the IP Address
250 *
251 * @access public
252 * @return string
253 */
254 function ip_address()
255 {
256 if ($this->ip_address !== FALSE)
257 {
258 return $this->ip_address;
259 }
260
261 $cip = (isset($_SERVER['HTTP_CLIENT_IP']) AND $_SERVER['HTTP_CLIENT_IP'] != "") ? $_SERVER['HTTP_CLIENT_IP'] : FALSE;
262 $rip = (isset($_SERVER['REMOTE_ADDR']) AND $_SERVER['REMOTE_ADDR'] != "") ? $_SERVER['REMOTE_ADDR'] : FALSE;
263 $fip = (isset($_SERVER['HTTP_X_FORWARDED_FOR']) AND $_SERVER['HTTP_X_FORWARDED_FOR'] != "") ? $_SERVER['HTTP_X_FORWARDED_FOR'] : FALSE;
264
265 if ($cip && $rip) $this->ip_address = $cip;
266 elseif ($rip) $this->ip_address = $rip;
267 elseif ($cip) $this->ip_address = $cip;
268 elseif ($fip) $this->ip_address = $fip;
269
270 if (strstr($this->ip_address, ','))
271 {
272 $x = explode(',', $this->ip_address);
273 $this->ip_address = end($x);
274 }
275
276 if ( ! $this->valid_ip($this->ip_address))
277 {
278 $this->ip_address = '0.0.0.0';
279 }
280
281 unset($cip);
282 unset($rip);
283 unset($fip);
284
285 return $this->ip_address;
286 }
287 // END ip_address()
288
289 // --------------------------------------------------------------------
290
291 /**
292 * Validate IP Address
293 *
294 * @access public
295 * @param string
296 * @return string
297 */
298 function valid_ip($ip)
299 {
300 return ( ! preg_match( "/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/", $ip)) ? FALSE : TRUE;
301 }
302 // END valid_ip()
303
304 // --------------------------------------------------------------------
305
306 /**
307 * User Agent
308 *
309 * @access public
310 * @return string
311 */
312 function user_agent()
313 {
314 if ($this->user_agent !== FALSE)
315 {
316 return $this->user_agent;
317 }
318
319 $this->user_agent = ( ! isset($_SERVER['HTTP_USER_AGENT'])) ? FALSE : $_SERVER['HTTP_USER_AGENT'];
320
321 return $this->user_agent;
322 }
323 // END user_agent()
324
325 // --------------------------------------------------------------------
326
327 /**
328 * XSS Clean
329 *
330 * Sanitizes data so that Cross Site Scripting Hacks can be
331 * prevented.Ê This function does a fair amount of work but
332 * it is extremely thorough, designed to prevent even the
333 * most obscure XSS attempts.Ê Nothing is ever 100% foolproof,
334 * of course, but I haven't been able to get anything passed
335 * the filter.
336 *
337 * Note: This function should only be used to deal with data
338 * upon submission.Ê It's not something that should
339 * be used for general runtime processing.
340 *
341 * This function was based in part on some code and ideas I
342 * got from Bitflux: http://blog.bitflux.ch/wiki/XSS_Prevention
343 *
344 * To help develop this script I used this great list of
345 * vulnerabilities along with a few other hacks I've
346 * harvested from examining vulnerabilities in other programs:
347 * http://ha.ckers.org/xss.html
348 *
349 * @access public
350 * @param string
351 * @return string
352 */
353 function xss_clean($str, $charset = 'ISO-8859-1')
354 {
355 /*
356 * Remove Null Characters
357 *
358 * This prevents sandwiching null characters
359 * between ascii characters, like Java\0script.
360 *
361 */
362 $str = preg_replace('/\0+/', '', $str);
363 $str = preg_replace('/(\\\\0)+/', '', $str);
364
365 /*
366 * Validate standard character entites
367 *
368 * Add a semicolon if missing. We do this to enable
369 * the conversion of entities to ASCII later.
370 *
371 */
372 $str = preg_replace('#(&\#*\w+)[\x00-\x20]+;#u',"\\1;",$str);
373
374 /*
375 * Validate UTF16 two byte encodeing (x00)
376 *
377 * Just as above, adds a semicolon if missing.
378 *
379 */
380 $str = preg_replace('#(&\#x*)([0-9A-F]+);*#iu',"\\1\\2;",$str);
381
382 /*
383 * URL Decode
384 *
385 * Just in case stuff like this is submitted:
386 *
387 * <a href="http://%77%77%77%2E%67%6F%6F%67%6C%65%2E%63%6F%6D">Google</a>
388 *
389 * Note: Normally urldecode() would be easier but it removes plus signs
390 *
391 */
392 $str = preg_replace("/%u0([a-z0-9]{3})/i", "&#x\\1;", $str);
393 $str = preg_replace("/%([a-z0-9]{2})/i", "&#x\\1;", $str);
394
395 /*
396 * Convert character entities to ASCII
397 *
398 * This permits our tests below to work reliably.
399 * We only convert entities that are within tags since
400 * these are the ones that will pose security problems.
401 *
402 */
403
404 if (preg_match_all("/<(.+?)>/si", $str, $matches))
405 {
406 for ($i = 0; $i < count($matches['0']); $i++)
407 {
408 $str = str_replace($matches['1'][$i],
409 $this->_html_entity_decode($matches['1'][$i], $charset),
410 $str);
411 }
412 }
413
414 /*
415 * Convert all tabs to spaces
416 *
417 * This prevents strings like this: ja vascript
418 * Note: we deal with spaces between characters later.
419 *
420 */
421 $str = preg_replace("#\t+#", " ", $str);
422
423 /*
424 * Makes PHP tags safe
425 *
426 * Note: XML tags are inadvertently replaced too:
427 *
428 * <?xml
429 *
430 * But it doesn't seem to pose a problem.
431 *
432 */
adminbc042dd2006-09-21 02:46:59 +0000433 $str = str_replace(array('<?php', '<?PHP', '<?', '?>'), array('&lt;?php', '&lt;?PHP', '&lt;?', '?&gt;'), $str);
adminb0dd10f2006-08-25 17:25:49 +0000434
435 /*
436 * Compact any exploded words
437 *
438 * This corrects words like: j a v a s c r i p t
439 * These words are compacted back to their correct state.
440 *
441 */
442 $words = array('javascript', 'vbscript', 'script', 'applet', 'alert', 'document', 'write', 'cookie', 'window');
443 foreach ($words as $word)
444 {
445 $temp = '';
446 for ($i = 0; $i < strlen($word); $i++)
447 {
448 $temp .= substr($word, $i, 1)."\s*";
449 }
450
451 $temp = substr($temp, 0, -3);
452 $str = preg_replace('#'.$temp.'#s', $word, $str);
453 $str = preg_replace('#'.ucfirst($temp).'#s', ucfirst($word), $str);
454 }
455
456 /*
457 * Remove disallowed Javascript in links or img tags
458 */
459 $str = preg_replace("#<a.+?href=.*?(alert\(|alert&\#40;|javascript\:|window\.|document\.|\.cookie|<script|<xss).*?\>.*?</a>#si", "", $str);
460 $str = preg_replace("#<img.+?src=.*?(alert\(|alert&\#40;|javascript\:|window\.|document\.|\.cookie|<script|<xss).*?\>#si", "", $str);
461 $str = preg_replace("#<(script|xss).*?\>#si", "", $str);
462
463 /*
464 * Remove JavaScript Event Handlers
465 *
466 * Note: This code is a little blunt. It removes
467 * the event handler and anything up to the closing >,
468 * but it's unlkely to be a problem.
469 *
470 */
471 $str = preg_replace('#(<[^>]+.*?)(onblur|onchange|onclick|onfocus|onload|onmouseover|onmouseup|onmousedown|onselect|onsubmit|onunload|onkeypress|onkeydown|onkeyup|onresize)[^>]*>#iU',"\\1>",$str);
472
473 /*
474 * Sanitize naughty HTML elements
475 *
476 * If a tag containing any of the words in the list
477 * below is found, the tag gets converted to entities.
478 *
479 * So this: <blink>
480 * Becomes: &lt;blink&gt;
481 *
482 */
483 $str = preg_replace('#<(/*\s*)(alert|applet|basefont|base|behavior|bgsound|blink|body|embed|expression|form|frameset|frame|head|html|ilayer|iframe|input|layer|link|meta|object|plaintext|style|script|textarea|title|xml|xss)([^>]*)>#is', "&lt;\\1\\2\\3&gt;", $str);
484
485 /*
486 * Sanitize naughty scripting elements
487 *
488 * Similar to above, only instead of looking for
489 * tags it looks for PHP and JavaScript commands
490 * that are disallowed. Rather than removing the
491 * code, it simply converts the parenthesis to entities
492 * rendering the code unexecutable.
493 *
494 * For example: eval('some code')
495 * Becomes: eval&#40;'some code'&#41;
496 *
497 */
498 $str = preg_replace('#(alert|cmd|passthru|eval|exec|system|fopen|fsockopen|file|file_get_contents|readfile|unlink)(\s*)\((.*?)\)#si', "\\1\\2&#40;\\3&#41;", $str);
499
500 /*
501 * Final clean up
502 *
503 * This adds a bit of extra precaution in case
504 * something got through the above filters
505 *
506 */
507 $bad = array(
508 'document.cookie' => '',
509 'document.write' => '',
510 'window.location' => '',
511 "javascript\s*:" => '',
512 "Redirect\s+302" => '',
513 '<!--' => '&lt;!--',
514 '-->' => '--&gt;'
515 );
516
517 foreach ($bad as $key => $val)
518 {
519 $str = preg_replace("#".$key."#i", $val, $str);
520 }
521
522
523 log_message('debug', "XSS Filtering completed");
524 return $str;
525 }
526 // END xss_clean()
527
528
529 /**
530 * HTML Entities Decode
531 *
532 * This function is a replacement for html_entity_decode()
533 *
534 * In some versions of PHP the native function does not work
535 * when UTF-8 is the specified character set, so this gives us
536 * a work-around. More info here:
537 * http://bugs.php.net/bug.php?id=25670
538 *
539 * @access private
540 * @param string
541 * @param string
542 * @return string
543 */
544 /* -------------------------------------------------
545 /* Replacement for html_entity_decode()
546 /* -------------------------------------------------*/
547
548 /*
549 NOTE: html_entity_decode() has a bug in some PHP versions when UTF-8 is the
550 character set, and the PHP developers said they were not back porting the
551 fix to versions other than PHP 5.x.
552 */
553 function _html_entity_decode($str, $charset='ISO-8859-1')
554 {
555 if (stristr($str, '&') === FALSE) return $str;
556
557 // The reason we are not using html_entity_decode() by itself is because
558 // while it is not technically correct to leave out the semicolon
559 // at the end of an entity most browsers will still interpret the entity
560 // correctly. html_entity_decode() does not convert entities without
561 // semicolons, so we are left with our own little solution here. Bummer.
562
563 if (function_exists('html_entity_decode') && (strtolower($charset) != 'utf-8' OR version_compare(phpversion(), '5.0.0', '>=')))
564 {
565 $str = html_entity_decode($str, ENT_COMPAT, $charset);
566 $str = preg_replace('~&#x([0-9a-f]{2,5})~ei', 'chr(hexdec("\\1"))', $str);
567 return preg_replace('~&#([0-9]{2,4})~e', 'chr(\\1)', $str);
568 }
569
570 // Numeric Entities
571 $str = preg_replace('~&#x([0-9a-f]{2,5});{0,1}~ei', 'chr(hexdec("\\1"))', $str);
572 $str = preg_replace('~&#([0-9]{2,4});{0,1}~e', 'chr(\\1)', $str);
573
574 // Literal Entities - Slightly slow so we do another check
575 if (stristr($str, '&') === FALSE)
576 {
577 $str = strtr($str, array_flip(get_html_translation_table(HTML_ENTITIES)));
578 }
579
580 return $str;
581 }
582
583}
584// END Input class
585?>