Subversion Repositories Applications.papyrus

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
2005 Aurelien 1
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
2
/**
3
 * CodeIgniter
4
 *
5
 * An open source application development framework for PHP 4.3.2 or newer
6
 *
7
 * @package		CodeIgniter
8
 * @author		ExpressionEngine Dev Team
9
 * @copyright	Copyright (c) 2008, EllisLab, Inc.
10
 * @license		http://codeigniter.com/user_guide/license.html
11
 * @link		http://codeigniter.com
12
 * @since		Version 1.0
13
 * @filesource
14
 */
15
16
// ------------------------------------------------------------------------
17
18
/**
19
 * Input Class
20
 *
21
 * Pre-processes global input data for security
22
 *
23
 * @package		CodeIgniter
24
 * @subpackage	Libraries
25
 * @category	Input
26
 * @author		ExpressionEngine Dev Team
27
 * @link		http://codeigniter.com/user_guide/libraries/input.html
28
 */
29
class CI_Input {
30
	var $use_xss_clean		= FALSE;
31
	var $xss_hash			= '';
32
	var $ip_address			= FALSE;
33
	var $user_agent			= FALSE;
34
	var $allow_get_array	= FALSE;
35
36
	/* never allowed, string replacement */
37
	var $never_allowed_str = array(
38
									'document.cookie'	=> '[removed]',
39
									'document.write'	=> '[removed]',
40
									'.parentNode'		=> '[removed]',
41
									'.innerHTML'		=> '[removed]',
42
									'window.location'	=> '[removed]',
43
									'-moz-binding'		=> '[removed]',
44
									'<!--'				=> '&lt;!--',
45
									'-->'				=> '--&gt;',
46
									'<![CDATA['			=> '&lt;![CDATA['
47
									);
48
	/* never allowed, regex replacement */
49
	var $never_allowed_regex = array(
50
										"javascript\s*:"	=> '[removed]',
51
										"expression\s*\("	=> '[removed]', // CSS and IE
52
										"Redirect\s+302"	=> '[removed]'
53
									);
54
55
	/**
56
	 * Constructor
57
	 *
58
	 * Sets whether to globally enable the XSS processing
59
	 * and whether to allow the $_GET array
60
	 *
61
	 * @access	public
62
	 */
63
	function CI_Input()
64
	{
65
		log_message('debug', "Input Class Initialized");
66
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();
71
	}
72
73
	// --------------------------------------------------------------------
74
75
	/**
76
	 * Sanitize Globals
77
	 *
78
	 * This function does the following:
79
	 *
80
	 * Unsets $_GET data (if query strings are not enabled)
81
	 *
82
	 * Unsets all globals if register_globals is enabled
83
	 *
84
	 * Standardizes newline characters to \n
85
	 *
86
	 * @access	private
87
	 * @return	void
88
	 */
89
	function _sanitize_globals()
90
	{
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');
94
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)
98
		{
99
			if ( ! is_array($global))
100
			{
101
				if ( ! in_array($global, $protected))
102
				{
103
					unset($GLOBALS[$global]);
104
				}
105
			}
106
			else
107
			{
108
				foreach ($global as $key => $val)
109
				{
110
					if ( ! in_array($key, $protected))
111
					{
112
						unset($GLOBALS[$key]);
113
					}
114
115
					if (is_array($val))
116
					{
117
						foreach($val as $k => $v)
118
						{
119
							if ( ! in_array($k, $protected))
120
							{
121
								unset($GLOBALS[$k]);
122
							}
123
						}
124
					}
125
				}
126
			}
127
		}
128
129
		// Is $_GET data allowed? If not we'll set the $_GET to an empty array
130
		if ($this->allow_get_array == FALSE)
131
		{
132
			$_GET = array();
133
		}
134
		else
135
		{
136
			$_GET = $this->_clean_input_data($_GET);
137
		}
138
139
		// Clean $_POST Data
140
		$_POST = $this->_clean_input_data($_POST);
141
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);
152
153
		log_message('debug', "Global POST and COOKIE data sanitized");
154
	}
155
156
	// --------------------------------------------------------------------
157
158
	/**
159
	 * Clean Input Data
160
	 *
161
	 * This is a helper function. It escapes data and
162
	 * standardizes newline characters to \n
163
	 *
164
	 * @access	private
165
	 * @param	string
166
	 * @return	string
167
	 */
168
	function _clean_input_data($str)
169
	{
170
		if (is_array($str))
171
		{
172
			$new_array = array();
173
			foreach ($str as $key => $val)
174
			{
175
				$new_array[$this->_clean_input_keys($key)] = $this->_clean_input_data($val);
176
			}
177
			return $new_array;
178
		}
179
180
		// We strip slashes if magic quotes is on to keep things consistent
181
		if (get_magic_quotes_gpc())
182
		{
183
			$str = stripslashes($str);
184
		}
185
186
		// Should we filter the input data?
187
		if ($this->use_xss_clean === TRUE)
188
		{
189
			$str = $this->xss_clean($str);
190
		}
191
192
		// Standardize newlines
193
		if (strpos($str, "\r") !== FALSE)
194
		{
195
			$str = str_replace(array("\r\n", "\r"), "\n", $str);
196
		}
197
198
		return $str;
199
	}
200
201
	// --------------------------------------------------------------------
202
203
	/**
204
	 * Clean Keys
205
	 *
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.
209
	 *
210
	 * @access	private
211
	 * @param	string
212
	 * @return	string
213
	 */
214
	function _clean_input_keys($str)
215
	{
216
		 if ( ! preg_match("/^[a-z0-9:_\/-]+$/i", $str))
217
		 {
218
			exit('Disallowed Key Characters.');
219
		 }
220
221
		return $str;
222
	}
223
224
	// --------------------------------------------------------------------
225
226
	/**
227
	 * Fetch from array
228
	 *
229
	 * This is a helper function to retrieve values from global arrays
230
	 *
231
	 * @access	private
232
	 * @param	array
233
	 * @param	string
234
	 * @param	bool
235
	 * @return	string
236
	 */
237
	function _fetch_from_array(&$array, $index = '', $xss_clean = FALSE)
238
	{
239
		if ( ! isset($array[$index]))
240
		{
241
			return FALSE;
242
		}
243
244
		if ($xss_clean === TRUE)
245
		{
246
			return $this->xss_clean($array[$index]);
247
		}
248
249
		return $array[$index];
250
	}
251
252
	// --------------------------------------------------------------------
253
254
	/**
255
	 * Fetch an item from the GET array
256
	 *
257
	 * @access	public
258
	 * @param	string
259
	 * @param	bool
260
	 * @return	string
261
	 */
262
	function get($index = '', $xss_clean = FALSE)
263
	{
264
		return $this->_fetch_from_array($_GET, $index, $xss_clean);
265
	}
266
267
	// --------------------------------------------------------------------
268
269
	/**
270
	 * Fetch an item from the POST array
271
	 *
272
	 * @access	public
273
	 * @param	string
274
	 * @param	bool
275
	 * @return	string
276
	 */
277
	function post($index = '', $xss_clean = FALSE)
278
	{
279
		return $this->_fetch_from_array($_POST, $index, $xss_clean);
280
	}
281
282
	// --------------------------------------------------------------------
283
284
	/**
285
	 * Fetch an item from either the GET array or the POST
286
	 *
287
	 * @access	public
288
	 * @param	string	The index key
289
	 * @param	bool	XSS cleaning
290
	 * @return	string
291
	 */
292
	function get_post($index = '', $xss_clean = FALSE)
293
	{
294
		if ( ! isset($_POST[$index]) )
295
		{
296
			return $this->get($index, $xss_clean);
297
		}
298
		else
299
		{
300
			return $this->post($index, $xss_clean);
301
		}
302
	}
303
304
	// --------------------------------------------------------------------
305
306
	/**
307
	 * Fetch an item from the COOKIE array
308
	 *
309
	 * @access	public
310
	 * @param	string
311
	 * @param	bool
312
	 * @return	string
313
	 */
314
	function cookie($index = '', $xss_clean = FALSE)
315
	{
316
		return $this->_fetch_from_array($_COOKIE, $index, $xss_clean);
317
	}
318
319
	// --------------------------------------------------------------------
320
321
	/**
322
	 * Fetch an item from the SERVER array
323
	 *
324
	 * @access	public
325
	 * @param	string
326
	 * @param	bool
327
	 * @return	string
328
	 */
329
	function server($index = '', $xss_clean = FALSE)
330
	{
331
		return $this->_fetch_from_array($_SERVER, $index, $xss_clean);
332
	}
333
334
	// --------------------------------------------------------------------
335
336
	/**
337
	 * Fetch the IP Address
338
	 *
339
	 * @access	public
340
	 * @return	string
341
	 */
342
	function ip_address()
343
	{
344
		if ($this->ip_address !== FALSE)
345
		{
346
			return $this->ip_address;
347
		}
348
349
		if ($this->server('REMOTE_ADDR') AND $this->server('HTTP_CLIENT_IP'))
350
		{
351
			 $this->ip_address = $_SERVER['HTTP_CLIENT_IP'];
352
		}
353
		elseif ($this->server('REMOTE_ADDR'))
354
		{
355
			 $this->ip_address = $_SERVER['REMOTE_ADDR'];
356
		}
357
		elseif ($this->server('HTTP_CLIENT_IP'))
358
		{
359
			 $this->ip_address = $_SERVER['HTTP_CLIENT_IP'];
360
		}
361
		elseif ($this->server('HTTP_X_FORWARDED_FOR'))
362
		{
363
			 $this->ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
364
		}
365
366
		if ($this->ip_address === FALSE)
367
		{
368
			$this->ip_address = '0.0.0.0';
369
			return $this->ip_address;
370
		}
371
372
		if (strstr($this->ip_address, ','))
373
		{
374
			$x = explode(',', $this->ip_address);
375
			$this->ip_address = end($x);
376
		}
377
378
		if ( ! $this->valid_ip($this->ip_address))
379
		{
380
			$this->ip_address = '0.0.0.0';
381
		}
382
383
		return $this->ip_address;
384
	}
385
386
	// --------------------------------------------------------------------
387
388
	/**
389
	 * Validate IP Address
390
	 *
391
	 * Updated version suggested by Geert De Deckere
392
	 *
393
	 * @access	public
394
	 * @param	string
395
	 * @return	string
396
	 */
397
	function valid_ip($ip)
398
	{
399
		$ip_segments = explode('.', $ip);
400
401
		// Always 4 segments needed
402
		if (count($ip_segments) != 4)
403
		{
404
			return FALSE;
405
		}
406
		// IP can not start with 0
407
		if ($ip_segments[0][0] == '0')
408
		{
409
			return FALSE;
410
		}
411
		// Check each segment
412
		foreach ($ip_segments as $segment)
413
		{
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)
417
			{
418
				return FALSE;
419
			}
420
		}
421
422
		return TRUE;
423
	}
424
425
	// --------------------------------------------------------------------
426
427
	/**
428
	 * User Agent
429
	 *
430
	 * @access	public
431
	 * @return	string
432
	 */
433
	function user_agent()
434
	{
435
		if ($this->user_agent !== FALSE)
436
		{
437
			return $this->user_agent;
438
		}
439
440
		$this->user_agent = ( ! isset($_SERVER['HTTP_USER_AGENT'])) ? FALSE : $_SERVER['HTTP_USER_AGENT'];
441
442
		return $this->user_agent;
443
	}
444
445
	// --------------------------------------------------------------------
446
447
	/**
448
	 * Filename Security
449
	 *
450
	 * @access	public
451
	 * @param	string
452
	 * @return	string
453
	 */
454
	function filename_security($str)
455
	{
456
		$bad = array(
457
						"../",
458
						"./",
459
						"<!--",
460
						"-->",
461
						"<",
462
						">",
463
						"'",
464
						'"',
465
						'&',
466
						'$',
467
						'#',
468
						'{',
469
						'}',
470
						'[',
471
						']',
472
						'=',
473
						';',
474
						'?',
475
						"%20",
476
						"%22",
477
						"%3c",		// <
478
						"%253c", 	// <
479
						"%3e", 		// >
480
						"%0e", 		// >
481
						"%28", 		// (
482
						"%29", 		// )
483
						"%2528", 	// (
484
						"%26", 		// &
485
						"%24", 		// $
486
						"%3f", 		// ?
487
						"%3b", 		// ;
488
						"%3d"		// =
489
					);
490
491
		return stripslashes(str_replace($bad, '', $str));
492
	}
493
494
	// --------------------------------------------------------------------
495
496
	/**
497
	 * XSS Clean
498
	 *
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
504
	 * the filter.
505
	 *
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.
509
	 *
510
	 * This function was based in part on some code and ideas I
511
	 * got from Bitflux: http://blog.bitflux.ch/wiki/XSS_Prevention
512
	 *
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
517
	 *
518
	 * @access	public
519
	 * @param	string
520
	 * @return	string
521
	 */
522
	function xss_clean($str, $is_image = FALSE)
523
	{
524
		/*
525
		 * Is the string an array?
526
		 *
527
		 */
528
		if (is_array($str))
529
		{
530
			while (list($key) = each($str))
531
			{
532
				$str[$key] = $this->xss_clean($str[$key]);
533
			}
534
535
			return $str;
536
		}
537
538
		/*
539
		 * Remove Invisible Characters
540
		 */
541
		$str = $this->_remove_invisible_characters($str);
542
543
		/*
544
		 * Protect GET variables in URLs
545
		 */
546
547
		 // 901119URL5918AMP18930PROTECT8198
548
549
		$str = preg_replace('|\&([a-z\_0-9]+)\=([a-z\_0-9]+)|i', $this->xss_hash()."\\1=\\2", $str);
550
551
		/*
552
		 * Validate standard character entities
553
		 *
554
		 * Add a semicolon if missing.  We do this to enable
555
		 * the conversion of entities to ASCII later.
556
		 *
557
		 */
558
		$str = preg_replace('#(&\#?[0-9a-z]{2,})[\x00-\x20]*;?#i', "\\1;", $str);
559
560
		/*
561
		 * Validate UTF16 two byte encoding (x00)
562
		 *
563
		 * Just as above, adds a semicolon if missing.
564
		 *
565
		 */
566
		$str = preg_replace('#(&\#x?)([0-9A-F]+);?#i',"\\1\\2;",$str);
567
568
		/*
569
		 * Un-Protect GET variables in URLs
570
		 */
571
		$str = str_replace($this->xss_hash(), '&', $str);
572
573
		/*
574
		 * URL Decode
575
		 *
576
		 * Just in case stuff like this is submitted:
577
		 *
578
		 * <a href="http://%77%77%77%2E%67%6F%6F%67%6C%65%2E%63%6F%6D">Google</a>
579
		 *
580
		 * Note: Use rawurldecode() so it does not remove plus signs
581
		 *
582
		 */
583
		$str = rawurldecode($str);
584
585
		/*
586
		 * Convert character entities to ASCII
587
		 *
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.
591
		 *
592
		 */
593
594
		$str = preg_replace_callback("/[a-z]+=([\'\"]).*?\\1/si", array($this, '_convert_attribute'), $str);
595
596
		$str = preg_replace_callback("/<\w+.*?(?=>|<|$)/si", array($this, '_html_entity_decode_callback'), $str);
597
598
		/*
599
		 * Remove Invisible Characters Again!
600
		 */
601
		$str = $this->_remove_invisible_characters($str);
602
603
		/*
604
		 * Convert all tabs to spaces
605
		 *
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.
610
		 *
611
		 */
612
613
 		if (strpos($str, "\t") !== FALSE)
614
		{
615
			$str = str_replace("\t", ' ', $str);
616
		}
617
618
		/*
619
		 * Capture converted string for later comparison
620
		 */
621
		$converted_string = $str;
622
623
		/*
624
		 * Not Allowed Under Any Conditions
625
		 */
626
627
		foreach ($this->never_allowed_str as $key => $val)
628
		{
629
			$str = str_replace($key, $val, $str);
630
		}
631
632
		foreach ($this->never_allowed_regex as $key => $val)
633
		{
634
			$str = preg_replace("#".$key."#i", $val, $str);
635
		}
636
637
		/*
638
		 * Makes PHP tags safe
639
		 *
640
		 *  Note: XML tags are inadvertently replaced too:
641
		 *
642
		 *	<?xml
643
		 *
644
		 * But it doesn't seem to pose a problem.
645
		 *
646
		 */
647
		if ($is_image === TRUE)
648
		{
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('&lt;?php', '&lt;?PHP'), $str);
652
		}
653
		else
654
		{
655
			$str = str_replace(array('<?php', '<?PHP', '<?', '?'.'>'),  array('&lt;?php', '&lt;?PHP', '&lt;?', '?&gt;'), $str);
656
		}
657
658
		/*
659
		 * Compact any exploded words
660
		 *
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.
663
		 *
664
		 */
665
		$words = array('javascript', 'expression', 'vbscript', 'script', 'applet', 'alert', 'document', 'write', 'cookie', 'window');
666
		foreach ($words as $word)
667
		{
668
			$temp = '';
669
670
			for ($i = 0, $wordlen = strlen($word); $i < $wordlen; $i++)
671
			{
672
				$temp .= substr($word, $i, 1)."\s*";
673
			}
674
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);
678
		}
679
680
		/*
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
684
		 */
685
		do
686
		{
687
			$original = $str;
688
689
			if (preg_match("/<a/i", $str))
690
			{
691
				$str = preg_replace_callback("#<a\s+([^>]*?)(>|$)#si", array($this, '_js_link_removal'), $str);
692
			}
693
694
			if (preg_match("/<img/i", $str))
695
			{
696
				$str = preg_replace_callback("#<img\s+([^>]*?)(\s?/?>|$)#si", array($this, '_js_img_removal'), $str);
697
			}
698
699
			if (preg_match("/script/i", $str) OR preg_match("/xss/i", $str))
700
			{
701
				$str = preg_replace("#<(/*)(script|xss)(.*?)\>#si", '[removed]', $str);
702
			}
703
		}
704
		while($original != $str);
705
706
		unset($original);
707
708
		/*
709
		 * Remove JavaScript Event Handlers
710
		 *
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.
714
		 *
715
		 */
716
		$event_handlers = array('[^a-z_\-]on\w*','xmlns');
717
718
		if ($is_image === TRUE)
719
		{
720
			/*
721
			 * Adobe Photoshop puts XML metadata into JFIF images, including namespacing,
722
			 * so we have to allow this for images. -Paul
723
			 */
724
			unset($event_handlers[array_search('xmlns', $event_handlers)]);
725
		}
726
727
		$str = preg_replace("#<([^><]+?)(".implode('|', $event_handlers).")(\s*=\s*[^><]*)([><]*)#i", "<\\1\\4", $str);
728
729
		/*
730
		 * Sanitize naughty HTML elements
731
		 *
732
		 * If a tag containing any of the words in the list
733
		 * below is found, the tag gets converted to entities.
734
		 *
735
		 * So this: <blink>
736
		 * Becomes: &lt;blink&gt;
737
		 *
738
		 */
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);
741
742
		/*
743
		 * Sanitize naughty scripting elements
744
		 *
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.
750
		 *
751
		 * For example:	eval('some code')
752
		 * Becomes:		eval&#40;'some code'&#41;
753
		 *
754
		 */
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);
756
757
		/*
758
		 * Final clean up
759
		 *
760
		 * This adds a bit of extra precaution in case
761
		 * something got through the above filters
762
		 *
763
		 */
764
		foreach ($this->never_allowed_str as $key => $val)
765
		{
766
			$str = str_replace($key, $val, $str);
767
		}
768
769
		foreach ($this->never_allowed_regex as $key => $val)
770
		{
771
			$str = preg_replace("#".$key."#i", $val, $str);
772
		}
773
774
		/*
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.
780
		 */
781
782
		if ($is_image === TRUE)
783
		{
784
			if ($str == $converted_string)
785
			{
786
				return TRUE;
787
			}
788
			else
789
			{
790
				return FALSE;
791
			}
792
		}
793
794
		log_message('debug', "XSS Filtering completed");
795
		return $str;
796
	}
797
798
	// --------------------------------------------------------------------
799
800
	/**
801
	 * Random Hash for protecting URLs
802
	 *
803
	 * @access	public
804
	 * @return	string
805
	 */
806
	function xss_hash()
807
	{
808
		if ($this->xss_hash == '')
809
		{
810
			if (phpversion() >= 4.2)
811
				mt_srand();
812
			else
813
				mt_srand(hexdec(substr(md5(microtime()), -8)) & 0x7fffffff);
814
815
			$this->xss_hash = md5(time() + mt_rand(0, 1999999999));
816
		}
817
818
		return $this->xss_hash;
819
	}
820
821
	// --------------------------------------------------------------------
822
823
	/**
824
	 * Remove Invisible Characters
825
	 *
826
	 * This prevents sandwiching null characters
827
	 * between ascii characters, like Java\0script.
828
	 *
829
	 * @access	public
830
	 * @param	string
831
	 * @return	string
832
	 */
833
	function _remove_invisible_characters($str)
834
	{
835
		static $non_displayables;
836
837
		if ( ! isset($non_displayables))
838
		{
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
846
									);
847
		}
848
849
		do
850
		{
851
			$cleaned = $str;
852
			$str = preg_replace($non_displayables, '', $str);
853
		}
854
		while ($cleaned != $str);
855
856
		return $str;
857
	}
858
859
	// --------------------------------------------------------------------
860
861
	/**
862
	 * Compact Exploded Words
863
	 *
864
	 * Callback function for xss_clean() to remove whitespace from
865
	 * things like j a v a s c r i p t
866
	 *
867
	 * @access	public
868
	 * @param	type
869
	 * @return	type
870
	 */
871
	function _compact_exploded_words($matches)
872
	{
873
		return preg_replace('/\s+/s', '', $matches[1]).$matches[2];
874
	}
875
876
	// --------------------------------------------------------------------
877
878
	/**
879
	 * Sanitize Naughty HTML
880
	 *
881
	 * Callback function for xss_clean() to remove naughty HTML elements
882
	 *
883
	 * @access	private
884
	 * @param	array
885
	 * @return	string
886
	 */
887
	function _sanitize_naughty_html($matches)
888
	{
889
		// encode opening brace
890
		$str = '&lt;'.$matches[1].$matches[2].$matches[3];
891
892
		// encode captured opening or closing brace to prevent recursive vectors
893
		$str .= str_replace(array('>', '<'), array('&gt;', '&lt;'), $matches[4]);
894
895
		return $str;
896
	}
897
898
	// --------------------------------------------------------------------
899
900
	/**
901
	 * JS Link Removal
902
	 *
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
907
	 *
908
	 * @access	private
909
	 * @param	array
910
	 * @return	string
911
	 */
912
	function _js_link_removal($match)
913
	{
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]);
916
	}
917
918
	/**
919
	 * JS Image Removal
920
	 *
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
925
	 *
926
	 * @access	private
927
	 * @param	array
928
	 * @return	string
929
	 */
930
	function _js_img_removal($match)
931
	{
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]);
934
	}
935
936
	// --------------------------------------------------------------------
937
938
	/**
939
	 * Attribute Conversion
940
	 *
941
	 * Used as a callback for XSS Clean
942
	 *
943
	 * @access	public
944
	 * @param	array
945
	 * @return	string
946
	 */
947
	function _convert_attribute($match)
948
	{
949
		return str_replace(array('>', '<'), array('&gt;', '&lt;'), $match[0]);
950
	}
951
952
	// --------------------------------------------------------------------
953
954
	/**
955
	 * HTML Entity Decode Callback
956
	 *
957
	 * Used as a callback for XSS Clean
958
	 *
959
	 * @access	public
960
	 * @param	array
961
	 * @return	string
962
	 */
963
	function _html_entity_decode_callback($match)
964
	{
965
		$CFG =& load_class('Config');
966
		$charset = $CFG->item('charset');
967
968
		return $this->_html_entity_decode($match[0], strtoupper($charset));
969
	}
970
971
	// --------------------------------------------------------------------
972
973
	/**
974
	 * HTML Entities Decode
975
	 *
976
	 * This function is a replacement for html_entity_decode()
977
	 *
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
982
	 *
983
	 * @access	private
984
	 * @param	string
985
	 * @param	string
986
	 * @return	string
987
	 */
988
	/* -------------------------------------------------
989
	/*  Replacement for html_entity_decode()
990
	/* -------------------------------------------------*/
991
992
	/*
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.
996
	*/
997
	function _html_entity_decode($str, $charset='UTF-8')
998
	{
999
		if (stristr($str, '&') === FALSE) return $str;
1000
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.
1006
1007
		if (function_exists('html_entity_decode') && (strtolower($charset) != 'utf-8' OR version_compare(phpversion(), '5.0.0', '>=')))
1008
		{
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);
1012
		}
1013
1014
		// Numeric Entities
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);
1017
1018
		// Literal Entities - Slightly slow so we do another check
1019
		if (stristr($str, '&') === FALSE)
1020
		{
1021
			$str = strtr($str, array_flip(get_html_translation_table(HTML_ENTITIES)));
1022
		}
1023
1024
		return $str;
1025
	}
1026
1027
	// --------------------------------------------------------------------
1028
1029
	/**
1030
	 * Filter Attributes
1031
	 *
1032
	 * Filters tag attributes for consistency and safety
1033
	 *
1034
	 * @access	public
1035
	 * @param	string
1036
	 * @return	string
1037
	 */
1038
	function _filter_attributes($str)
1039
	{
1040
		$out = '';
1041
1042
		if (preg_match_all('#\s*[a-z\-]+\s*=\s*(\042|\047)([^\\1]*?)\\1#is', $str, $matches))
1043
		{
1044
			foreach ($matches[0] as $match)
1045
			{
1046
				$out .= "{$match}";
1047
			}
1048
		}
1049
1050
		return $out;
1051
	}
1052
1053
	// --------------------------------------------------------------------
1054
1055
}
1056
// END Input class
1057
1058
/* End of file Input.php */
1059
/* Location: ./system/libraries/Input.php */