blob: 4f91572ed6763cebed1a0a9ab73599d00845ea4d [file] [log] [blame]
Derek Jonese701d762010-03-02 18:17:01 -06001<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
2/**
3 * CodeIgniter
4 *
Greg Aker741de1c2010-11-10 14:52:57 -06005 * An open source application development framework for PHP 5.1.6 or newer
Derek Jonese701d762010-03-02 18:17:01 -06006 *
7 * @package CodeIgniter
8 * @author ExpressionEngine Dev Team
Greg Aker0711dc82011-01-05 10:49:40 -06009 * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
Derek Jonese701d762010-03-02 18:17:01 -060010 * @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 * Security Class
20 *
21 * @package CodeIgniter
22 * @subpackage Libraries
23 * @category Security
24 * @author ExpressionEngine Dev Team
Pascal Krietec9c045a2011-04-05 14:50:41 -040025 * @link http://codeigniter.com/user_guide/libraries/security.html
Derek Jonese701d762010-03-02 18:17:01 -060026 */
27class CI_Security {
Pascal Krietec9c045a2011-04-05 14:50:41 -040028
29 protected $_xss_hash = '';
30 protected $_csrf_hash = '';
31 protected $_csrf_expire = 7200; // Two hours (in seconds)
32 protected $_csrf_token_name = 'ci_csrf_token';
33 protected $_csrf_cookie_name = 'ci_csrf_token';
Barry Mienydd671972010-10-04 16:33:58 +020034
Derek Jonese701d762010-03-02 18:17:01 -060035 /* never allowed, string replacement */
Pascal Krietec9c045a2011-04-05 14:50:41 -040036 protected $_never_allowed_str = array(
37 'document.cookie' => '[removed]',
38 'document.write' => '[removed]',
39 '.parentNode' => '[removed]',
40 '.innerHTML' => '[removed]',
41 'window.location' => '[removed]',
42 '-moz-binding' => '[removed]',
43 '<!--' => '&lt;!--',
44 '-->' => '--&gt;',
45 '<![CDATA[' => '&lt;![CDATA['
46 );
Derek Jonese701d762010-03-02 18:17:01 -060047
Pascal Krietec9c045a2011-04-05 14:50:41 -040048 /* never allowed, regex replacement */
49 protected $_never_allowed_regex = array(
50 "javascript\s*:" => '[removed]',
51 "expression\s*(\(|&\#40;)" => '[removed]', // CSS and IE
52 "vbscript\s*:" => '[removed]', // IE, surprise!
53 "Redirect\s+302" => '[removed]'
54 );
55
56 /**
57 * Constructor
58 */
Greg Akera9263282010-11-10 15:26:43 -060059 public function __construct()
Derek Jonese701d762010-03-02 18:17:01 -060060 {
patworkef1a55a2011-04-09 13:04:06 +020061 // CSRF config
62 foreach(array('csrf_expire', 'csrf_token_name', 'csrf_cookie_name') as $key)
63 {
64 if (FALSE !== ($val = config_item($key)))
65 {
66 $this->{'_'.$key} = $val;
67 }
68 }
69
patwork9e267982011-04-11 13:02:32 +020070 // Append application specific cookie prefix
71 if (config_item('cookie_prefix')) {
72 $this->_csrf_cookie_name = config_item('cookie_prefix').$this->_csrf_cookie_name;
73 }
Derek Jonesb3f10a22010-07-25 19:11:26 -050074
Derek Jonese701d762010-03-02 18:17:01 -060075 // Set the CSRF hash
76 $this->_csrf_set_hash();
Derek Allard958543a2010-07-22 14:10:26 -040077
Derek Jonese701d762010-03-02 18:17:01 -060078 log_message('debug', "Security Class Initialized");
79 }
80
81 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +020082
Derek Jonese701d762010-03-02 18:17:01 -060083 /**
84 * Verify Cross Site Request Forgery Protection
85 *
Pascal Krietec9c045a2011-04-05 14:50:41 -040086 * @return object
Derek Jonese701d762010-03-02 18:17:01 -060087 */
Eric Barnes9805ecc2011-01-16 23:35:16 -050088 public function csrf_verify()
Derek Allard958543a2010-07-22 14:10:26 -040089 {
Derek Jonese701d762010-03-02 18:17:01 -060090 // If no POST data exists we will set the CSRF cookie
91 if (count($_POST) == 0)
92 {
93 return $this->csrf_set_cookie();
94 }
95
96 // Do the tokens exist in both the _POST and _COOKIE arrays?
Pascal Krietec9c045a2011-04-05 14:50:41 -040097 if ( ! isset($_POST[$this->_csrf_token_name]) OR
98 ! isset($_COOKIE[$this->_csrf_cookie_name]))
Derek Jonese701d762010-03-02 18:17:01 -060099 {
100 $this->csrf_show_error();
101 }
102
103 // Do the tokens match?
Pascal Krietec9c045a2011-04-05 14:50:41 -0400104 if ($_POST[$this->_csrf_token_name] != $_COOKIE[$this->_csrf_cookie_name])
Derek Jonese701d762010-03-02 18:17:01 -0600105 {
106 $this->csrf_show_error();
107 }
108
Pascal Krietec9c045a2011-04-05 14:50:41 -0400109 // We kill this since we're done and we don't want to
110 // polute the _POST array
111 unset($_POST[$this->_csrf_token_name]);
Barry Mienydd671972010-10-04 16:33:58 +0200112
Derek Jonesb3f10a22010-07-25 19:11:26 -0500113 // Nothing should last forever
Pascal Krietec9c045a2011-04-05 14:50:41 -0400114 unset($_COOKIE[$this->_csrf_cookie_name]);
Derek Jonesb3f10a22010-07-25 19:11:26 -0500115 $this->_csrf_set_hash();
116 $this->csrf_set_cookie();
Derek Jonese701d762010-03-02 18:17:01 -0600117
118 log_message('debug', "CSRF token verified ");
Pascal Krietec9c045a2011-04-05 14:50:41 -0400119
120 return $this;
Derek Jonese701d762010-03-02 18:17:01 -0600121 }
Barry Mienydd671972010-10-04 16:33:58 +0200122
Derek Jonese701d762010-03-02 18:17:01 -0600123 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200124
Derek Jonese701d762010-03-02 18:17:01 -0600125 /**
126 * Set Cross Site Request Forgery Protection Cookie
127 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400128 * @return object
Derek Jonese701d762010-03-02 18:17:01 -0600129 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500130 public function csrf_set_cookie()
Derek Jonese701d762010-03-02 18:17:01 -0600131 {
Pascal Krietec9c045a2011-04-05 14:50:41 -0400132 $expire = time() + $this->_csrf_expire;
Robin Sowell154da112011-02-11 15:33:44 -0500133 $secure_cookie = (config_item('cookie_secure') === TRUE) ? 1 : 0;
Derek Jonese701d762010-03-02 18:17:01 -0600134
Pascal Krietec9c045a2011-04-05 14:50:41 -0400135 if ($secure_cookie)
Derek Jonese701d762010-03-02 18:17:01 -0600136 {
Pascal Krietec9c045a2011-04-05 14:50:41 -0400137 $req = isset($_SERVER['HTTPS']) ? $_SERVER['HTTPS'] : FALSE;
138
139 if ( ! $req OR $req == 'off')
Derek Jonese701d762010-03-02 18:17:01 -0600140 {
Pascal Krietec9c045a2011-04-05 14:50:41 -0400141 return FALSE;
Derek Jonese701d762010-03-02 18:17:01 -0600142 }
143 }
Derek Allard958543a2010-07-22 14:10:26 -0400144
Pascal Krietec9c045a2011-04-05 14:50:41 -0400145 setcookie($this->_csrf_cookie_name, $this->_csrf_hash, $expire, config_item('cookie_path'), config_item('cookie_domain'), $secure_cookie);
146
147 log_message('debug', "CRSF cookie Set");
148
149 return $this;
Derek Jonese701d762010-03-02 18:17:01 -0600150 }
151
152 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200153
Derek Jonese701d762010-03-02 18:17:01 -0600154 /**
155 * Show CSRF Error
156 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400157 * @return void
Derek Jonese701d762010-03-02 18:17:01 -0600158 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500159 public function csrf_show_error()
Derek Jonese701d762010-03-02 18:17:01 -0600160 {
161 show_error('The action you have requested is not allowed.');
162 }
163
164 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200165
Derek Jonese701d762010-03-02 18:17:01 -0600166 /**
Pascal Krietec9c045a2011-04-05 14:50:41 -0400167 * Get CSRF Hash
168 *
169 * Getter Method
170 *
171 * @return string self::_csrf_hash
172 */
173 public function get_csrf_hash()
174 {
175 return $this->_csrf_hash;
176 }
177
178 // --------------------------------------------------------------------
179
180 /**
181 * Get CSRF Token Name
182 *
183 * Getter Method
184 *
185 * @return string self::csrf_token_name
186 */
187 public function get_csrf_token_name()
188 {
189 return $this->_csrf_token_name;
190 }
191
192 // --------------------------------------------------------------------
193
194 /**
Derek Jonese701d762010-03-02 18:17:01 -0600195 * XSS Clean
196 *
197 * Sanitizes data so that Cross Site Scripting Hacks can be
198 * prevented. This function does a fair amount of work but
199 * it is extremely thorough, designed to prevent even the
200 * most obscure XSS attempts. Nothing is ever 100% foolproof,
201 * of course, but I haven't been able to get anything passed
202 * the filter.
203 *
204 * Note: This function should only be used to deal with data
205 * upon submission. It's not something that should
206 * be used for general runtime processing.
207 *
208 * This function was based in part on some code and ideas I
209 * got from Bitflux: http://channel.bitflux.ch/wiki/XSS_Prevention
210 *
211 * To help develop this script I used this great list of
212 * vulnerabilities along with a few other hacks I've
213 * harvested from examining vulnerabilities in other programs:
214 * http://ha.ckers.org/xss.html
215 *
Derek Jonese701d762010-03-02 18:17:01 -0600216 * @param mixed string or array
217 * @return string
218 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500219 public function xss_clean($str, $is_image = FALSE)
Derek Jonese701d762010-03-02 18:17:01 -0600220 {
221 /*
222 * Is the string an array?
223 *
224 */
225 if (is_array($str))
226 {
227 while (list($key) = each($str))
228 {
229 $str[$key] = $this->xss_clean($str[$key]);
230 }
Barry Mienydd671972010-10-04 16:33:58 +0200231
Derek Jonese701d762010-03-02 18:17:01 -0600232 return $str;
233 }
234
235 /*
236 * Remove Invisible Characters
237 */
Greg Aker757dda62010-04-14 19:06:19 -0500238 $str = remove_invisible_characters($str);
Derek Jonese701d762010-03-02 18:17:01 -0600239
Pascal Krietec9c045a2011-04-05 14:50:41 -0400240 // Validate Entities in URLs
241 $str = $this->_validate_entities($str);
Derek Jonese701d762010-03-02 18:17:01 -0600242
243 /*
244 * URL Decode
245 *
246 * Just in case stuff like this is submitted:
247 *
248 * <a href="http://%77%77%77%2E%67%6F%6F%67%6C%65%2E%63%6F%6D">Google</a>
249 *
250 * Note: Use rawurldecode() so it does not remove plus signs
251 *
252 */
253 $str = rawurldecode($str);
Barry Mienydd671972010-10-04 16:33:58 +0200254
Derek Jonese701d762010-03-02 18:17:01 -0600255 /*
Barry Mienydd671972010-10-04 16:33:58 +0200256 * Convert character entities to ASCII
Derek Jonese701d762010-03-02 18:17:01 -0600257 *
258 * This permits our tests below to work reliably.
259 * We only convert entities that are within tags since
260 * these are the ones that will pose security problems.
261 *
262 */
263
264 $str = preg_replace_callback("/[a-z]+=([\'\"]).*?\\1/si", array($this, '_convert_attribute'), $str);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400265
Derek Jonese701d762010-03-02 18:17:01 -0600266 $str = preg_replace_callback("/<\w+.*?(?=>|<|$)/si", array($this, '_decode_entity'), $str);
267
268 /*
269 * Remove Invisible Characters Again!
270 */
Greg Aker757dda62010-04-14 19:06:19 -0500271 $str = remove_invisible_characters($str);
Barry Mienydd671972010-10-04 16:33:58 +0200272
Derek Jonese701d762010-03-02 18:17:01 -0600273 /*
274 * Convert all tabs to spaces
275 *
276 * This prevents strings like this: ja vascript
277 * NOTE: we deal with spaces between characters later.
Pascal Krietec9c045a2011-04-05 14:50:41 -0400278 * NOTE: preg_replace was found to be amazingly slow here on
279 * large blocks of data, so we use str_replace.
Derek Jonese701d762010-03-02 18:17:01 -0600280 */
Barry Mienydd671972010-10-04 16:33:58 +0200281
Derek Jonese701d762010-03-02 18:17:01 -0600282 if (strpos($str, "\t") !== FALSE)
283 {
284 $str = str_replace("\t", ' ', $str);
285 }
Barry Mienydd671972010-10-04 16:33:58 +0200286
Derek Jonese701d762010-03-02 18:17:01 -0600287 /*
288 * Capture converted string for later comparison
289 */
290 $converted_string = $str;
Barry Mienydd671972010-10-04 16:33:58 +0200291
Pascal Krietec9c045a2011-04-05 14:50:41 -0400292 // Remove Strings that are never allowed
293 $str = $this->_do_never_allowed($str);
Derek Jonese701d762010-03-02 18:17:01 -0600294
295 /*
296 * Makes PHP tags safe
297 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400298 * Note: XML tags are inadvertently replaced too:
Derek Jonese701d762010-03-02 18:17:01 -0600299 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400300 * <?xml
Derek Jonese701d762010-03-02 18:17:01 -0600301 *
302 * But it doesn't seem to pose a problem.
Derek Jonese701d762010-03-02 18:17:01 -0600303 */
304 if ($is_image === TRUE)
305 {
Pascal Krietec9c045a2011-04-05 14:50:41 -0400306 // Images have a tendency to have the PHP short opening and
307 // closing tags every so often so we skip those and only
308 // do the long opening tags.
Derek Jonese701d762010-03-02 18:17:01 -0600309 $str = preg_replace('/<\?(php)/i', "&lt;?\\1", $str);
310 }
311 else
312 {
313 $str = str_replace(array('<?', '?'.'>'), array('&lt;?', '?&gt;'), $str);
314 }
Barry Mienydd671972010-10-04 16:33:58 +0200315
Derek Jonese701d762010-03-02 18:17:01 -0600316 /*
317 * Compact any exploded words
318 *
319 * This corrects words like: j a v a s c r i p t
320 * These words are compacted back to their correct state.
Derek Jonese701d762010-03-02 18:17:01 -0600321 */
Pascal Krietec9c045a2011-04-05 14:50:41 -0400322 $words = array(
323 'javascript', 'expression', 'vbscript', 'script',
324 'applet', 'alert', 'document', 'write', 'cookie', 'window'
325 );
326
Derek Jonese701d762010-03-02 18:17:01 -0600327 foreach ($words as $word)
328 {
329 $temp = '';
Barry Mienydd671972010-10-04 16:33:58 +0200330
Derek Jonese701d762010-03-02 18:17:01 -0600331 for ($i = 0, $wordlen = strlen($word); $i < $wordlen; $i++)
332 {
333 $temp .= substr($word, $i, 1)."\s*";
334 }
335
336 // We only want to do this when it is followed by a non-word character
337 // That way valid stuff like "dealer to" does not become "dealerto"
338 $str = preg_replace_callback('#('.substr($temp, 0, -3).')(\W)#is', array($this, '_compact_exploded_words'), $str);
339 }
Barry Mienydd671972010-10-04 16:33:58 +0200340
Derek Jonese701d762010-03-02 18:17:01 -0600341 /*
342 * Remove disallowed Javascript in links or img tags
Pascal Krietec9c045a2011-04-05 14:50:41 -0400343 * We used to do some version comparisons and use of stripos for PHP5,
344 * but it is dog slow compared to these simplified non-capturing
345 * preg_match(), especially if the pattern exists in the string
Derek Jonese701d762010-03-02 18:17:01 -0600346 */
347 do
348 {
349 $original = $str;
Barry Mienydd671972010-10-04 16:33:58 +0200350
Derek Jonese701d762010-03-02 18:17:01 -0600351 if (preg_match("/<a/i", $str))
352 {
353 $str = preg_replace_callback("#<a\s+([^>]*?)(>|$)#si", array($this, '_js_link_removal'), $str);
354 }
Barry Mienydd671972010-10-04 16:33:58 +0200355
Derek Jonese701d762010-03-02 18:17:01 -0600356 if (preg_match("/<img/i", $str))
357 {
358 $str = preg_replace_callback("#<img\s+([^>]*?)(\s?/?>|$)#si", array($this, '_js_img_removal'), $str);
359 }
Barry Mienydd671972010-10-04 16:33:58 +0200360
Derek Jonese701d762010-03-02 18:17:01 -0600361 if (preg_match("/script/i", $str) OR preg_match("/xss/i", $str))
362 {
363 $str = preg_replace("#<(/*)(script|xss)(.*?)\>#si", '[removed]', $str);
364 }
365 }
Pascal Krietec9c045a2011-04-05 14:50:41 -0400366 while($original != $str);
Derek Jonese701d762010-03-02 18:17:01 -0600367
368 unset($original);
369
Pascal Krietec9c045a2011-04-05 14:50:41 -0400370 // Remove evil attributes such as style, onclick and xmlns
371 $str = $this->_remove_evil_attributes($str, $is_image);
Barry Mienydd671972010-10-04 16:33:58 +0200372
Derek Jonese701d762010-03-02 18:17:01 -0600373 /*
374 * Sanitize naughty HTML elements
375 *
376 * If a tag containing any of the words in the list
377 * below is found, the tag gets converted to entities.
378 *
379 * So this: <blink>
380 * Becomes: &lt;blink&gt;
Derek Jonese701d762010-03-02 18:17:01 -0600381 */
382 $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';
383 $str = preg_replace_callback('#<(/*\s*)('.$naughty.')([^><]*)([><]*)#is', array($this, '_sanitize_naughty_html'), $str);
384
385 /*
386 * Sanitize naughty scripting elements
387 *
388 * Similar to above, only instead of looking for
389 * tags it looks for PHP and JavaScript commands
390 * that are disallowed. Rather than removing the
391 * code, it simply converts the parenthesis to entities
392 * rendering the code un-executable.
393 *
394 * For example: eval('some code')
395 * Becomes: eval&#40;'some code'&#41;
Derek Jonese701d762010-03-02 18:17:01 -0600396 */
397 $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);
Barry Mienydd671972010-10-04 16:33:58 +0200398
Barry Mienydd671972010-10-04 16:33:58 +0200399
Pascal Krietec9c045a2011-04-05 14:50:41 -0400400 // Final clean up
401 // This adds a bit of extra precaution in case
402 // something got through the above filters
403 $str = $this->_do_never_allowed($str);
Derek Jonese701d762010-03-02 18:17:01 -0600404
405 /*
Pascal Krietec9c045a2011-04-05 14:50:41 -0400406 * Images are Handled in a Special Way
407 * - Essentially, we want to know that after all of the character
408 * conversion is done whether any unwanted, likely XSS, code was found.
409 * If not, we return TRUE, as the image is clean.
410 * However, if the string post-conversion does not matched the
411 * string post-removal of XSS, then it fails, as there was unwanted XSS
412 * code found and removed/changed during processing.
Derek Jonese701d762010-03-02 18:17:01 -0600413 */
414
415 if ($is_image === TRUE)
416 {
Pascal Krietec9c045a2011-04-05 14:50:41 -0400417 return ($str == $converted_string) ? TRUE: FALSE;
Derek Jonese701d762010-03-02 18:17:01 -0600418 }
Barry Mienydd671972010-10-04 16:33:58 +0200419
Derek Jonese701d762010-03-02 18:17:01 -0600420 log_message('debug', "XSS Filtering completed");
421 return $str;
422 }
423
424 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200425
Derek Jonese701d762010-03-02 18:17:01 -0600426 /**
427 * Random Hash for protecting URLs
428 *
Derek Jonese701d762010-03-02 18:17:01 -0600429 * @return string
430 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500431 public function xss_hash()
Barry Mienydd671972010-10-04 16:33:58 +0200432 {
Pascal Krietec9c045a2011-04-05 14:50:41 -0400433 if ($this->_xss_hash == '')
Derek Jonese701d762010-03-02 18:17:01 -0600434 {
435 if (phpversion() >= 4.2)
Derek Jonese701d762010-03-02 18:17:01 -0600436 {
Pascal Krietec9c045a2011-04-05 14:50:41 -0400437 mt_srand();
Derek Jonese701d762010-03-02 18:17:01 -0600438 }
Pascal Krietec9c045a2011-04-05 14:50:41 -0400439 else
440 {
441 mt_srand(hexdec(substr(md5(microtime()), -8)) & 0x7fffffff);
442 }
443
444 $this->_xss_hash = md5(time() + mt_rand(0, 1999999999));
Derek Jonese701d762010-03-02 18:17:01 -0600445 }
446
Pascal Krietec9c045a2011-04-05 14:50:41 -0400447 return $this->_xss_hash;
Derek Jonese701d762010-03-02 18:17:01 -0600448 }
449
450 // --------------------------------------------------------------------
451
452 /**
Derek Jonesa0911472010-03-30 10:33:09 -0500453 * HTML Entities Decode
454 *
455 * This function is a replacement for html_entity_decode()
456 *
457 * In some versions of PHP the native function does not work
458 * when UTF-8 is the specified character set, so this gives us
459 * a work-around. More info here:
460 * http://bugs.php.net/bug.php?id=25670
461 *
462 * NOTE: html_entity_decode() has a bug in some PHP versions when UTF-8 is the
463 * character set, and the PHP developers said they were not back porting the
464 * fix to versions other than PHP 5.x.
465 *
Derek Jonesa0911472010-03-30 10:33:09 -0500466 * @param string
467 * @param string
468 * @return string
469 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500470 public function entity_decode($str, $charset='UTF-8')
Derek Jonesa0911472010-03-30 10:33:09 -0500471 {
472 if (stristr($str, '&') === FALSE) return $str;
Barry Mienydd671972010-10-04 16:33:58 +0200473
Derek Jonesa0911472010-03-30 10:33:09 -0500474 // The reason we are not using html_entity_decode() by itself is because
475 // while it is not technically correct to leave out the semicolon
476 // at the end of an entity most browsers will still interpret the entity
477 // correctly. html_entity_decode() does not convert entities without
478 // semicolons, so we are left with our own little solution here. Bummer.
Barry Mienydd671972010-10-04 16:33:58 +0200479
Pascal Krietec9c045a2011-04-05 14:50:41 -0400480 if (function_exists('html_entity_decode') &&
481 (strtolower($charset) != 'utf-8'))
Derek Jonesa0911472010-03-30 10:33:09 -0500482 {
483 $str = html_entity_decode($str, ENT_COMPAT, $charset);
484 $str = preg_replace('~&#x(0*[0-9a-f]{2,5})~ei', 'chr(hexdec("\\1"))', $str);
485 return preg_replace('~&#([0-9]{2,4})~e', 'chr(\\1)', $str);
486 }
Barry Mienydd671972010-10-04 16:33:58 +0200487
Derek Jonesa0911472010-03-30 10:33:09 -0500488 // Numeric Entities
489 $str = preg_replace('~&#x(0*[0-9a-f]{2,5});{0,1}~ei', 'chr(hexdec("\\1"))', $str);
490 $str = preg_replace('~&#([0-9]{2,4});{0,1}~e', 'chr(\\1)', $str);
Barry Mienydd671972010-10-04 16:33:58 +0200491
Derek Jonesa0911472010-03-30 10:33:09 -0500492 // Literal Entities - Slightly slow so we do another check
493 if (stristr($str, '&') === FALSE)
494 {
495 $str = strtr($str, array_flip(get_html_translation_table(HTML_ENTITIES)));
496 }
Barry Mienydd671972010-10-04 16:33:58 +0200497
Derek Jonesa0911472010-03-30 10:33:09 -0500498 return $str;
499 }
Barry Mienydd671972010-10-04 16:33:58 +0200500
Derek Jonesa0911472010-03-30 10:33:09 -0500501 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200502
Derek Jonesa0911472010-03-30 10:33:09 -0500503 /**
Derek Jonese701d762010-03-02 18:17:01 -0600504 * Filename Security
505 *
Derek Jonese701d762010-03-02 18:17:01 -0600506 * @param string
507 * @return string
508 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500509 public function sanitize_filename($str, $relative_path = FALSE)
Derek Jonese701d762010-03-02 18:17:01 -0600510 {
511 $bad = array(
512 "../",
Derek Jonese701d762010-03-02 18:17:01 -0600513 "<!--",
514 "-->",
515 "<",
516 ">",
517 "'",
518 '"',
519 '&',
520 '$',
521 '#',
522 '{',
523 '}',
524 '[',
525 ']',
526 '=',
527 ';',
528 '?',
Derek Jonese701d762010-03-02 18:17:01 -0600529 "%20",
530 "%22",
531 "%3c", // <
Barry Mienydd671972010-10-04 16:33:58 +0200532 "%253c", // <
533 "%3e", // >
534 "%0e", // >
535 "%28", // (
536 "%29", // )
537 "%2528", // (
538 "%26", // &
539 "%24", // $
540 "%3f", // ?
541 "%3b", // ;
Derek Jonese701d762010-03-02 18:17:01 -0600542 "%3d" // =
543 );
Pascal Krietec9c045a2011-04-05 14:50:41 -0400544
Derek Jones2ef37592010-10-06 17:51:59 -0500545 if ( ! $relative_path)
546 {
547 $bad[] = './';
548 $bad[] = '/';
549 }
Derek Jonese701d762010-03-02 18:17:01 -0600550
Pascal Krietec9c045a2011-04-05 14:50:41 -0400551 $str = remove_invisible_characters($str, FALSE);
Derek Jonese701d762010-03-02 18:17:01 -0600552 return stripslashes(str_replace($bad, '', $str));
553 }
554
Pascal Krietec9c045a2011-04-05 14:50:41 -0400555 // ----------------------------------------------------------------
556
557 /**
558 * Compact Exploded Words
559 *
560 * Callback function for xss_clean() to remove whitespace from
561 * things like j a v a s c r i p t
562 *
563 * @param type
564 * @return type
565 */
566 protected function _compact_exploded_words($matches)
567 {
568 return preg_replace('/\s+/s', '', $matches[1]).$matches[2];
569 }
570
571 // --------------------------------------------------------------------
572
573 /*
574 * Remove Evil HTML Attributes (like evenhandlers and style)
575 *
576 * It removes the evil attribute and either:
577 * - Everything up until a space
578 * For example, everything between the pipes:
579 * <a |style=document.write('hello');alert('world');| class=link>
580 * - Everything inside the quotes
581 * For example, everything between the pipes:
582 * <a |style="document.write('hello'); alert('world');"| class="link">
583 *
584 * @param string $str The string to check
585 * @param boolean $is_image TRUE if this is an image
586 * @return string The string with the evil attributes removed
587 */
588 protected function _remove_evil_attributes($str, $is_image)
589 {
590 // All javascript event handlers (e.g. onload, onclick, onmouseover), style, and xmlns
591 $evil_attributes = array('on\w*', 'style', 'xmlns');
592
593 if ($is_image === TRUE)
594 {
595 /*
596 * Adobe Photoshop puts XML metadata into JFIF images,
597 * including namespacing, so we have to allow this for images.
598 */
599 unset($evil_attributes[array_search('xmlns', $evil_attributes)]);
600 }
601
602 do {
603 $str = preg_replace(
604 "#<(/?[^><]+?)([^A-Za-z\-])(".implode('|', $evil_attributes).")(\s*=\s*)([\"][^>]*?[\"]|[\'][^>]*?[\']|[^>]*?)([\s><])([><]*)#i",
605 "<$1$6",
606 $str, -1, $count
607 );
608 } while ($count);
609
610 return $str;
611 }
612
613 // --------------------------------------------------------------------
614
615 /**
616 * Sanitize Naughty HTML
617 *
618 * Callback function for xss_clean() to remove naughty HTML elements
619 *
620 * @param array
621 * @return string
622 */
623 protected function _sanitize_naughty_html($matches)
624 {
625 // encode opening brace
626 $str = '&lt;'.$matches[1].$matches[2].$matches[3];
627
628 // encode captured opening or closing brace to prevent recursive vectors
629 $str .= str_replace(array('>', '<'), array('&gt;', '&lt;'),
630 $matches[4]);
631
632 return $str;
633 }
634
635 // --------------------------------------------------------------------
636
637 /**
638 * JS Link Removal
639 *
640 * Callback function for xss_clean() to sanitize links
641 * This limits the PCRE backtracks, making it more performance friendly
642 * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in
643 * PHP 5.2+ on link-heavy strings
644 *
645 * @param array
646 * @return string
647 */
648 protected function _js_link_removal($match)
649 {
650 $attributes = $this->_filter_attributes(str_replace(array('<', '>'), '', $match[1]));
651
652 return str_replace($match[1], preg_replace("#href=.*?(alert\(|alert&\#40;|javascript\:|livescript\:|mocha\:|charset\=|window\.|document\.|\.cookie|<script|<xss|base64\s*,)#si", "", $attributes), $match[0]);
653 }
654
655 // --------------------------------------------------------------------
656
657 /**
658 * JS Image Removal
659 *
660 * Callback function for xss_clean() to sanitize image tags
661 * This limits the PCRE backtracks, making it more performance friendly
662 * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in
663 * PHP 5.2+ on image tag heavy strings
664 *
665 * @param array
666 * @return string
667 */
668 protected function _js_img_removal($match)
669 {
670 $attributes = $this->_filter_attributes(str_replace(array('<', '>'), '', $match[1]));
671
672 return str_replace($match[1], preg_replace("#src=.*?(alert\(|alert&\#40;|javascript\:|livescript\:|mocha\:|charset\=|window\.|document\.|\.cookie|<script|<xss|base64\s*,)#si", "", $attributes), $match[0]);
673 }
674
675 // --------------------------------------------------------------------
676
677 /**
678 * Attribute Conversion
679 *
680 * Used as a callback for XSS Clean
681 *
682 * @param array
683 * @return string
684 */
685 protected function _convert_attribute($match)
686 {
687 return str_replace(array('>', '<', '\\'), array('&gt;', '&lt;', '\\\\'), $match[0]);
688 }
689
690 // --------------------------------------------------------------------
691
692 /**
693 * Filter Attributes
694 *
695 * Filters tag attributes for consistency and safety
696 *
697 * @param string
698 * @return string
699 */
700 protected function _filter_attributes($str)
701 {
702 $out = '';
703
704 if (preg_match_all('#\s*[a-z\-]+\s*=\s*(\042|\047)([^\\1]*?)\\1#is', $str, $matches))
705 {
706 foreach ($matches[0] as $match)
707 {
708 $out .= preg_replace("#/\*.*?\*/#s", '', $match);
709 }
710 }
711
712 return $out;
713 }
714
715 // --------------------------------------------------------------------
716
717 /**
718 * HTML Entity Decode Callback
719 *
720 * Used as a callback for XSS Clean
721 *
722 * @param array
723 * @return string
724 */
725 protected function _decode_entity($match)
726 {
727 return $this->entity_decode($match[0], strtoupper(config_item('charset')));
728 }
729
730 // --------------------------------------------------------------------
731
732 /**
733 * Validate URL entities
734 *
735 * Called by xss_clean()
736 *
737 * @param string
738 * @return string
739 */
740 protected function _validate_entities($str)
741 {
742 /*
743 * Protect GET variables in URLs
744 */
745
746 // 901119URL5918AMP18930PROTECT8198
747
748 $str = preg_replace('|\&([a-z\_0-9\-]+)\=([a-z\_0-9\-]+)|i', $this->xss_hash()."\\1=\\2", $str);
749
750 /*
751 * Validate standard character entities
752 *
753 * Add a semicolon if missing. We do this to enable
754 * the conversion of entities to ASCII later.
755 *
756 */
757 $str = preg_replace('#(&\#?[0-9a-z]{2,})([\x00-\x20])*;?#i', "\\1;\\2", $str);
758
759 /*
760 * Validate UTF16 two byte encoding (x00)
761 *
762 * Just as above, adds a semicolon if missing.
763 *
764 */
765 $str = preg_replace('#(&\#x?)([0-9A-F]+);?#i',"\\1\\2;",$str);
766
767 /*
768 * Un-Protect GET variables in URLs
769 */
770 $str = str_replace($this->xss_hash(), '&', $str);
771
772 return $str;
773 }
774
775 // ----------------------------------------------------------------------
776
777 /**
778 * Do Never Allowed
779 *
780 * A utility function for xss_clean()
781 *
782 * @param string
783 * @return string
784 */
785 protected function _do_never_allowed($str)
786 {
787 foreach ($this->_never_allowed_str as $key => $val)
788 {
789 $str = str_replace($key, $val, $str);
790 }
791
792 foreach ($this->_never_allowed_regex as $key => $val)
793 {
794 $str = preg_replace("#".$key."#i", $val, $str);
795 }
796
797 return $str;
798 }
799
800 // --------------------------------------------------------------------
801
802 /**
803 * Set Cross Site Request Forgery Protection Cookie
804 *
805 * @return string
806 */
807 protected function _csrf_set_hash()
808 {
809 if ($this->_csrf_hash == '')
810 {
811 // If the cookie exists we will use it's value.
812 // We don't necessarily want to regenerate it with
813 // each page load since a page could contain embedded
814 // sub-pages causing this feature to fail
815 if (isset($_COOKIE[$this->_csrf_cookie_name]) &&
816 $_COOKIE[$this->_csrf_cookie_name] != '')
817 {
818 return $this->_csrf_hash = $_COOKIE[$this->_csrf_cookie_name];
819 }
820
821 return $this->_csrf_hash = md5(uniqid(rand(), TRUE));
822 }
823
824 return $this->_csrf_hash;
825 }
826
Derek Jonese701d762010-03-02 18:17:01 -0600827}
828// END Security Class
829
830/* End of file Security.php */
patworkef1a55a2011-04-09 13:04:06 +0200831/* Location: ./system/libraries/Security.php */