blob: efd30eb14df4cae20bd430fbdcb91b1112f01dbf [file] [log] [blame]
Derek Jones4b9c6292011-07-01 17:40:48 -05001<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
Derek Jonese701d762010-03-02 18:17:01 -06002/**
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 {
Derek Jones4b9c6292011-07-01 17:40:48 -050028
Pascal Krietec9c045a2011-04-05 14:50:41 -040029 protected $_xss_hash = '';
30 protected $_csrf_hash = '';
Derek Jones4b9c6292011-07-01 17:40:48 -050031 protected $_csrf_expire = 7200; // Two hours (in seconds)
Pascal Krietec9c045a2011-04-05 14:50:41 -040032 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 );
Derek Jones4b9c6292011-07-01 17:40:48 -050055
Pascal Krietec9c045a2011-04-05 14:50:41 -040056 /**
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
Greg Akerb3e614d2011-04-19 20:19:17 -050071 if (config_item('cookie_prefix'))
72 {
patwork9e267982011-04-11 13:02:32 +020073 $this->_csrf_cookie_name = config_item('cookie_prefix').$this->_csrf_cookie_name;
74 }
Derek Jonesb3f10a22010-07-25 19:11:26 -050075
Derek Jonese701d762010-03-02 18:17:01 -060076 // Set the CSRF hash
77 $this->_csrf_set_hash();
Derek Allard958543a2010-07-22 14:10:26 -040078
Derek Jonese701d762010-03-02 18:17:01 -060079 log_message('debug', "Security Class Initialized");
80 }
81
82 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +020083
Derek Jonese701d762010-03-02 18:17:01 -060084 /**
85 * Verify Cross Site Request Forgery Protection
86 *
Pascal Krietec9c045a2011-04-05 14:50:41 -040087 * @return object
Derek Jonese701d762010-03-02 18:17:01 -060088 */
Eric Barnes9805ecc2011-01-16 23:35:16 -050089 public function csrf_verify()
Derek Allard958543a2010-07-22 14:10:26 -040090 {
Derek Jonese701d762010-03-02 18:17:01 -060091 // If no POST data exists we will set the CSRF cookie
92 if (count($_POST) == 0)
93 {
94 return $this->csrf_set_cookie();
95 }
Alex Bilbieaeb2c3e2011-08-21 16:14:54 +010096
97 // Check if URI has been whitelisted from CSRF checks
98 if ($exclude_uris = config_item('csrf_exclude_uris'))
99 {
100 $uri = load_class('URI', 'core');
101 if (in_array($uri->uri_string(), $exclude_uris))
102 {
103 return $this;
104 }
105 }
Derek Jonese701d762010-03-02 18:17:01 -0600106
107 // Do the tokens exist in both the _POST and _COOKIE arrays?
Derek Jones4b9c6292011-07-01 17:40:48 -0500108 if ( ! isset($_POST[$this->_csrf_token_name]) OR
Pascal Krietec9c045a2011-04-05 14:50:41 -0400109 ! isset($_COOKIE[$this->_csrf_cookie_name]))
Derek Jonese701d762010-03-02 18:17:01 -0600110 {
111 $this->csrf_show_error();
112 }
113
114 // Do the tokens match?
Pascal Krietec9c045a2011-04-05 14:50:41 -0400115 if ($_POST[$this->_csrf_token_name] != $_COOKIE[$this->_csrf_cookie_name])
Derek Jonese701d762010-03-02 18:17:01 -0600116 {
117 $this->csrf_show_error();
118 }
119
Derek Jones4b9c6292011-07-01 17:40:48 -0500120 // We kill this since we're done and we don't want to
Pascal Krietec9c045a2011-04-05 14:50:41 -0400121 // polute the _POST array
122 unset($_POST[$this->_csrf_token_name]);
Barry Mienydd671972010-10-04 16:33:58 +0200123
Derek Jonesb3f10a22010-07-25 19:11:26 -0500124 // Nothing should last forever
Pascal Krietec9c045a2011-04-05 14:50:41 -0400125 unset($_COOKIE[$this->_csrf_cookie_name]);
Derek Jonesb3f10a22010-07-25 19:11:26 -0500126 $this->_csrf_set_hash();
127 $this->csrf_set_cookie();
Derek Jonese701d762010-03-02 18:17:01 -0600128
Alex Bilbieaeb2c3e2011-08-21 16:14:54 +0100129 log_message('debug', "CSRF token verified");
Derek Jones4b9c6292011-07-01 17:40:48 -0500130
Pascal Krietec9c045a2011-04-05 14:50:41 -0400131 return $this;
Derek Jonese701d762010-03-02 18:17:01 -0600132 }
Barry Mienydd671972010-10-04 16:33:58 +0200133
Derek Jonese701d762010-03-02 18:17:01 -0600134 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200135
Derek Jonese701d762010-03-02 18:17:01 -0600136 /**
137 * Set Cross Site Request Forgery Protection Cookie
138 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400139 * @return object
Derek Jonese701d762010-03-02 18:17:01 -0600140 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500141 public function csrf_set_cookie()
Derek Jonese701d762010-03-02 18:17:01 -0600142 {
Pascal Krietec9c045a2011-04-05 14:50:41 -0400143 $expire = time() + $this->_csrf_expire;
Robin Sowell154da112011-02-11 15:33:44 -0500144 $secure_cookie = (config_item('cookie_secure') === TRUE) ? 1 : 0;
Derek Jonese701d762010-03-02 18:17:01 -0600145
Pascal Krietec9c045a2011-04-05 14:50:41 -0400146 if ($secure_cookie)
Derek Jonese701d762010-03-02 18:17:01 -0600147 {
Pascal Krietec9c045a2011-04-05 14:50:41 -0400148 $req = isset($_SERVER['HTTPS']) ? $_SERVER['HTTPS'] : FALSE;
149
150 if ( ! $req OR $req == 'off')
Derek Jonese701d762010-03-02 18:17:01 -0600151 {
Pascal Krietec9c045a2011-04-05 14:50:41 -0400152 return FALSE;
Derek Jonese701d762010-03-02 18:17:01 -0600153 }
154 }
Derek Allard958543a2010-07-22 14:10:26 -0400155
Pascal Krietec9c045a2011-04-05 14:50:41 -0400156 setcookie($this->_csrf_cookie_name, $this->_csrf_hash, $expire, config_item('cookie_path'), config_item('cookie_domain'), $secure_cookie);
157
158 log_message('debug', "CRSF cookie Set");
Derek Jones4b9c6292011-07-01 17:40:48 -0500159
Pascal Krietec9c045a2011-04-05 14:50:41 -0400160 return $this;
Derek Jonese701d762010-03-02 18:17:01 -0600161 }
162
163 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200164
Derek Jonese701d762010-03-02 18:17:01 -0600165 /**
166 * Show CSRF Error
167 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400168 * @return void
Derek Jonese701d762010-03-02 18:17:01 -0600169 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500170 public function csrf_show_error()
Derek Jonese701d762010-03-02 18:17:01 -0600171 {
172 show_error('The action you have requested is not allowed.');
173 }
174
175 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200176
Derek Jonese701d762010-03-02 18:17:01 -0600177 /**
Derek Jones4b9c6292011-07-01 17:40:48 -0500178 * Get CSRF Hash
Pascal Krietec9c045a2011-04-05 14:50:41 -0400179 *
Derek Jones4b9c6292011-07-01 17:40:48 -0500180 * Getter Method
Pascal Krietec9c045a2011-04-05 14:50:41 -0400181 *
182 * @return string self::_csrf_hash
183 */
184 public function get_csrf_hash()
185 {
186 return $this->_csrf_hash;
187 }
188
189 // --------------------------------------------------------------------
190
191 /**
192 * Get CSRF Token Name
193 *
194 * Getter Method
195 *
196 * @return string self::csrf_token_name
197 */
198 public function get_csrf_token_name()
199 {
200 return $this->_csrf_token_name;
201 }
202
203 // --------------------------------------------------------------------
204
205 /**
Derek Jonese701d762010-03-02 18:17:01 -0600206 * XSS Clean
207 *
208 * Sanitizes data so that Cross Site Scripting Hacks can be
Derek Jones4b9c6292011-07-01 17:40:48 -0500209 * prevented. This function does a fair amount of work but
Derek Jonese701d762010-03-02 18:17:01 -0600210 * it is extremely thorough, designed to prevent even the
Derek Jones4b9c6292011-07-01 17:40:48 -0500211 * most obscure XSS attempts. Nothing is ever 100% foolproof,
Derek Jonese701d762010-03-02 18:17:01 -0600212 * of course, but I haven't been able to get anything passed
213 * the filter.
214 *
215 * Note: This function should only be used to deal with data
Derek Jones4b9c6292011-07-01 17:40:48 -0500216 * upon submission. It's not something that should
Derek Jonese701d762010-03-02 18:17:01 -0600217 * be used for general runtime processing.
218 *
219 * This function was based in part on some code and ideas I
220 * got from Bitflux: http://channel.bitflux.ch/wiki/XSS_Prevention
221 *
222 * To help develop this script I used this great list of
223 * vulnerabilities along with a few other hacks I've
224 * harvested from examining vulnerabilities in other programs:
225 * http://ha.ckers.org/xss.html
226 *
Derek Jonese701d762010-03-02 18:17:01 -0600227 * @param mixed string or array
228 * @return string
229 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500230 public function xss_clean($str, $is_image = FALSE)
Derek Jonese701d762010-03-02 18:17:01 -0600231 {
232 /*
233 * Is the string an array?
234 *
235 */
236 if (is_array($str))
237 {
238 while (list($key) = each($str))
239 {
240 $str[$key] = $this->xss_clean($str[$key]);
241 }
Barry Mienydd671972010-10-04 16:33:58 +0200242
Derek Jonese701d762010-03-02 18:17:01 -0600243 return $str;
244 }
245
246 /*
247 * Remove Invisible Characters
248 */
Greg Aker757dda62010-04-14 19:06:19 -0500249 $str = remove_invisible_characters($str);
Derek Jonese701d762010-03-02 18:17:01 -0600250
Pascal Krietec9c045a2011-04-05 14:50:41 -0400251 // Validate Entities in URLs
252 $str = $this->_validate_entities($str);
Derek Jonese701d762010-03-02 18:17:01 -0600253
254 /*
255 * URL Decode
256 *
257 * Just in case stuff like this is submitted:
258 *
259 * <a href="http://%77%77%77%2E%67%6F%6F%67%6C%65%2E%63%6F%6D">Google</a>
260 *
261 * Note: Use rawurldecode() so it does not remove plus signs
262 *
263 */
264 $str = rawurldecode($str);
Barry Mienydd671972010-10-04 16:33:58 +0200265
Derek Jonese701d762010-03-02 18:17:01 -0600266 /*
Barry Mienydd671972010-10-04 16:33:58 +0200267 * Convert character entities to ASCII
Derek Jonese701d762010-03-02 18:17:01 -0600268 *
269 * This permits our tests below to work reliably.
270 * We only convert entities that are within tags since
271 * these are the ones that will pose security problems.
272 *
273 */
274
275 $str = preg_replace_callback("/[a-z]+=([\'\"]).*?\\1/si", array($this, '_convert_attribute'), $str);
Derek Jones4b9c6292011-07-01 17:40:48 -0500276
Derek Jonese701d762010-03-02 18:17:01 -0600277 $str = preg_replace_callback("/<\w+.*?(?=>|<|$)/si", array($this, '_decode_entity'), $str);
278
279 /*
280 * Remove Invisible Characters Again!
281 */
Greg Aker757dda62010-04-14 19:06:19 -0500282 $str = remove_invisible_characters($str);
Barry Mienydd671972010-10-04 16:33:58 +0200283
Derek Jonese701d762010-03-02 18:17:01 -0600284 /*
285 * Convert all tabs to spaces
286 *
287 * This prevents strings like this: ja vascript
288 * NOTE: we deal with spaces between characters later.
Derek Jones4b9c6292011-07-01 17:40:48 -0500289 * NOTE: preg_replace was found to be amazingly slow here on
Pascal Krietec9c045a2011-04-05 14:50:41 -0400290 * large blocks of data, so we use str_replace.
Derek Jonese701d762010-03-02 18:17:01 -0600291 */
Barry Mienydd671972010-10-04 16:33:58 +0200292
Derek Jonese701d762010-03-02 18:17:01 -0600293 if (strpos($str, "\t") !== FALSE)
294 {
295 $str = str_replace("\t", ' ', $str);
296 }
Barry Mienydd671972010-10-04 16:33:58 +0200297
Derek Jonese701d762010-03-02 18:17:01 -0600298 /*
299 * Capture converted string for later comparison
300 */
301 $converted_string = $str;
Barry Mienydd671972010-10-04 16:33:58 +0200302
Pascal Krietec9c045a2011-04-05 14:50:41 -0400303 // Remove Strings that are never allowed
304 $str = $this->_do_never_allowed($str);
Derek Jonese701d762010-03-02 18:17:01 -0600305
306 /*
307 * Makes PHP tags safe
308 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400309 * Note: XML tags are inadvertently replaced too:
Derek Jonese701d762010-03-02 18:17:01 -0600310 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400311 * <?xml
Derek Jonese701d762010-03-02 18:17:01 -0600312 *
313 * But it doesn't seem to pose a problem.
Derek Jonese701d762010-03-02 18:17:01 -0600314 */
315 if ($is_image === TRUE)
316 {
Derek Jones4b9c6292011-07-01 17:40:48 -0500317 // Images have a tendency to have the PHP short opening and
318 // closing tags every so often so we skip those and only
Pascal Krietec9c045a2011-04-05 14:50:41 -0400319 // do the long opening tags.
Derek Jonese701d762010-03-02 18:17:01 -0600320 $str = preg_replace('/<\?(php)/i', "&lt;?\\1", $str);
321 }
322 else
323 {
Derek Jones4b9c6292011-07-01 17:40:48 -0500324 $str = str_replace(array('<?', '?'.'>'), array('&lt;?', '?&gt;'), $str);
Derek Jonese701d762010-03-02 18:17:01 -0600325 }
Barry Mienydd671972010-10-04 16:33:58 +0200326
Derek Jonese701d762010-03-02 18:17:01 -0600327 /*
328 * Compact any exploded words
329 *
Derek Jones4b9c6292011-07-01 17:40:48 -0500330 * This corrects words like: j a v a s c r i p t
Derek Jonese701d762010-03-02 18:17:01 -0600331 * These words are compacted back to their correct state.
Derek Jonese701d762010-03-02 18:17:01 -0600332 */
Pascal Krietec9c045a2011-04-05 14:50:41 -0400333 $words = array(
Derek Jones4b9c6292011-07-01 17:40:48 -0500334 'javascript', 'expression', 'vbscript', 'script',
Pascal Krietec9c045a2011-04-05 14:50:41 -0400335 'applet', 'alert', 'document', 'write', 'cookie', 'window'
336 );
Derek Jones4b9c6292011-07-01 17:40:48 -0500337
Derek Jonese701d762010-03-02 18:17:01 -0600338 foreach ($words as $word)
339 {
340 $temp = '';
Barry Mienydd671972010-10-04 16:33:58 +0200341
Derek Jonese701d762010-03-02 18:17:01 -0600342 for ($i = 0, $wordlen = strlen($word); $i < $wordlen; $i++)
343 {
344 $temp .= substr($word, $i, 1)."\s*";
345 }
346
347 // We only want to do this when it is followed by a non-word character
348 // That way valid stuff like "dealer to" does not become "dealerto"
349 $str = preg_replace_callback('#('.substr($temp, 0, -3).')(\W)#is', array($this, '_compact_exploded_words'), $str);
350 }
Barry Mienydd671972010-10-04 16:33:58 +0200351
Derek Jonese701d762010-03-02 18:17:01 -0600352 /*
353 * Remove disallowed Javascript in links or img tags
Derek Jones4b9c6292011-07-01 17:40:48 -0500354 * We used to do some version comparisons and use of stripos for PHP5,
355 * but it is dog slow compared to these simplified non-capturing
Pascal Krietec9c045a2011-04-05 14:50:41 -0400356 * preg_match(), especially if the pattern exists in the string
Derek Jonese701d762010-03-02 18:17:01 -0600357 */
358 do
359 {
360 $original = $str;
Barry Mienydd671972010-10-04 16:33:58 +0200361
Derek Jonese701d762010-03-02 18:17:01 -0600362 if (preg_match("/<a/i", $str))
363 {
364 $str = preg_replace_callback("#<a\s+([^>]*?)(>|$)#si", array($this, '_js_link_removal'), $str);
365 }
Barry Mienydd671972010-10-04 16:33:58 +0200366
Derek Jonese701d762010-03-02 18:17:01 -0600367 if (preg_match("/<img/i", $str))
368 {
369 $str = preg_replace_callback("#<img\s+([^>]*?)(\s?/?>|$)#si", array($this, '_js_img_removal'), $str);
370 }
Barry Mienydd671972010-10-04 16:33:58 +0200371
Derek Jonese701d762010-03-02 18:17:01 -0600372 if (preg_match("/script/i", $str) OR preg_match("/xss/i", $str))
373 {
374 $str = preg_replace("#<(/*)(script|xss)(.*?)\>#si", '[removed]', $str);
375 }
376 }
Pascal Krietec9c045a2011-04-05 14:50:41 -0400377 while($original != $str);
Derek Jonese701d762010-03-02 18:17:01 -0600378
379 unset($original);
380
Pascal Krietec9c045a2011-04-05 14:50:41 -0400381 // Remove evil attributes such as style, onclick and xmlns
382 $str = $this->_remove_evil_attributes($str, $is_image);
Barry Mienydd671972010-10-04 16:33:58 +0200383
Derek Jonese701d762010-03-02 18:17:01 -0600384 /*
385 * Sanitize naughty HTML elements
386 *
387 * If a tag containing any of the words in the list
388 * below is found, the tag gets converted to entities.
389 *
390 * So this: <blink>
391 * Becomes: &lt;blink&gt;
Derek Jonese701d762010-03-02 18:17:01 -0600392 */
393 $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';
394 $str = preg_replace_callback('#<(/*\s*)('.$naughty.')([^><]*)([><]*)#is', array($this, '_sanitize_naughty_html'), $str);
395
396 /*
397 * Sanitize naughty scripting elements
398 *
399 * Similar to above, only instead of looking for
400 * tags it looks for PHP and JavaScript commands
Derek Jones4b9c6292011-07-01 17:40:48 -0500401 * that are disallowed. Rather than removing the
Derek Jonese701d762010-03-02 18:17:01 -0600402 * code, it simply converts the parenthesis to entities
403 * rendering the code un-executable.
404 *
405 * For example: eval('some code')
406 * Becomes: eval&#40;'some code'&#41;
Derek Jonese701d762010-03-02 18:17:01 -0600407 */
408 $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 +0200409
Barry Mienydd671972010-10-04 16:33:58 +0200410
Pascal Krietec9c045a2011-04-05 14:50:41 -0400411 // Final clean up
412 // This adds a bit of extra precaution in case
413 // something got through the above filters
414 $str = $this->_do_never_allowed($str);
Derek Jonese701d762010-03-02 18:17:01 -0600415
416 /*
Pascal Krietec9c045a2011-04-05 14:50:41 -0400417 * Images are Handled in a Special Way
Derek Jones4b9c6292011-07-01 17:40:48 -0500418 * - Essentially, we want to know that after all of the character
419 * conversion is done whether any unwanted, likely XSS, code was found.
Pascal Krietec9c045a2011-04-05 14:50:41 -0400420 * If not, we return TRUE, as the image is clean.
Derek Jones4b9c6292011-07-01 17:40:48 -0500421 * However, if the string post-conversion does not matched the
422 * string post-removal of XSS, then it fails, as there was unwanted XSS
Pascal Krietec9c045a2011-04-05 14:50:41 -0400423 * code found and removed/changed during processing.
Derek Jonese701d762010-03-02 18:17:01 -0600424 */
425
426 if ($is_image === TRUE)
427 {
Pascal Krietec9c045a2011-04-05 14:50:41 -0400428 return ($str == $converted_string) ? TRUE: FALSE;
Derek Jonese701d762010-03-02 18:17:01 -0600429 }
Barry Mienydd671972010-10-04 16:33:58 +0200430
Derek Jonese701d762010-03-02 18:17:01 -0600431 log_message('debug', "XSS Filtering completed");
432 return $str;
433 }
434
435 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200436
Derek Jonese701d762010-03-02 18:17:01 -0600437 /**
438 * Random Hash for protecting URLs
439 *
Derek Jonese701d762010-03-02 18:17:01 -0600440 * @return string
441 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500442 public function xss_hash()
Barry Mienydd671972010-10-04 16:33:58 +0200443 {
Pascal Krietec9c045a2011-04-05 14:50:41 -0400444 if ($this->_xss_hash == '')
Derek Jonese701d762010-03-02 18:17:01 -0600445 {
446 if (phpversion() >= 4.2)
Derek Jonese701d762010-03-02 18:17:01 -0600447 {
Pascal Krietec9c045a2011-04-05 14:50:41 -0400448 mt_srand();
Derek Jonese701d762010-03-02 18:17:01 -0600449 }
Pascal Krietec9c045a2011-04-05 14:50:41 -0400450 else
451 {
452 mt_srand(hexdec(substr(md5(microtime()), -8)) & 0x7fffffff);
453 }
454
455 $this->_xss_hash = md5(time() + mt_rand(0, 1999999999));
Derek Jonese701d762010-03-02 18:17:01 -0600456 }
457
Pascal Krietec9c045a2011-04-05 14:50:41 -0400458 return $this->_xss_hash;
Derek Jonese701d762010-03-02 18:17:01 -0600459 }
460
461 // --------------------------------------------------------------------
462
463 /**
Derek Jonesa0911472010-03-30 10:33:09 -0500464 * HTML Entities Decode
465 *
466 * This function is a replacement for html_entity_decode()
467 *
468 * In some versions of PHP the native function does not work
469 * when UTF-8 is the specified character set, so this gives us
Derek Jones4b9c6292011-07-01 17:40:48 -0500470 * a work-around. More info here:
Derek Jonesa0911472010-03-30 10:33:09 -0500471 * http://bugs.php.net/bug.php?id=25670
472 *
473 * NOTE: html_entity_decode() has a bug in some PHP versions when UTF-8 is the
474 * character set, and the PHP developers said they were not back porting the
475 * fix to versions other than PHP 5.x.
476 *
Derek Jonesa0911472010-03-30 10:33:09 -0500477 * @param string
478 * @param string
479 * @return string
480 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500481 public function entity_decode($str, $charset='UTF-8')
Derek Jonesa0911472010-03-30 10:33:09 -0500482 {
483 if (stristr($str, '&') === FALSE) return $str;
Barry Mienydd671972010-10-04 16:33:58 +0200484
Derek Jonesa0911472010-03-30 10:33:09 -0500485 // The reason we are not using html_entity_decode() by itself is because
486 // while it is not technically correct to leave out the semicolon
487 // at the end of an entity most browsers will still interpret the entity
Derek Jones4b9c6292011-07-01 17:40:48 -0500488 // correctly. html_entity_decode() does not convert entities without
Derek Jonesa0911472010-03-30 10:33:09 -0500489 // semicolons, so we are left with our own little solution here. Bummer.
Barry Mienydd671972010-10-04 16:33:58 +0200490
Derek Jones4b9c6292011-07-01 17:40:48 -0500491 if (function_exists('html_entity_decode') &&
Pascal Krietec9c045a2011-04-05 14:50:41 -0400492 (strtolower($charset) != 'utf-8'))
Derek Jonesa0911472010-03-30 10:33:09 -0500493 {
494 $str = html_entity_decode($str, ENT_COMPAT, $charset);
495 $str = preg_replace('~&#x(0*[0-9a-f]{2,5})~ei', 'chr(hexdec("\\1"))', $str);
496 return preg_replace('~&#([0-9]{2,4})~e', 'chr(\\1)', $str);
497 }
Barry Mienydd671972010-10-04 16:33:58 +0200498
Derek Jonesa0911472010-03-30 10:33:09 -0500499 // Numeric Entities
500 $str = preg_replace('~&#x(0*[0-9a-f]{2,5});{0,1}~ei', 'chr(hexdec("\\1"))', $str);
501 $str = preg_replace('~&#([0-9]{2,4});{0,1}~e', 'chr(\\1)', $str);
Barry Mienydd671972010-10-04 16:33:58 +0200502
Derek Jonesa0911472010-03-30 10:33:09 -0500503 // Literal Entities - Slightly slow so we do another check
504 if (stristr($str, '&') === FALSE)
505 {
506 $str = strtr($str, array_flip(get_html_translation_table(HTML_ENTITIES)));
507 }
Barry Mienydd671972010-10-04 16:33:58 +0200508
Derek Jonesa0911472010-03-30 10:33:09 -0500509 return $str;
510 }
Barry Mienydd671972010-10-04 16:33:58 +0200511
Derek Jonesa0911472010-03-30 10:33:09 -0500512 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200513
Derek Jonesa0911472010-03-30 10:33:09 -0500514 /**
Derek Jonese701d762010-03-02 18:17:01 -0600515 * Filename Security
516 *
Derek Jonese701d762010-03-02 18:17:01 -0600517 * @param string
518 * @return string
519 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500520 public function sanitize_filename($str, $relative_path = FALSE)
Derek Jonese701d762010-03-02 18:17:01 -0600521 {
522 $bad = array(
523 "../",
Derek Jonese701d762010-03-02 18:17:01 -0600524 "<!--",
525 "-->",
526 "<",
527 ">",
528 "'",
529 '"',
530 '&',
531 '$',
532 '#',
533 '{',
534 '}',
535 '[',
536 ']',
537 '=',
538 ';',
539 '?',
Derek Jonese701d762010-03-02 18:17:01 -0600540 "%20",
541 "%22",
542 "%3c", // <
Barry Mienydd671972010-10-04 16:33:58 +0200543 "%253c", // <
544 "%3e", // >
545 "%0e", // >
546 "%28", // (
547 "%29", // )
548 "%2528", // (
549 "%26", // &
550 "%24", // $
551 "%3f", // ?
552 "%3b", // ;
Derek Jonese701d762010-03-02 18:17:01 -0600553 "%3d" // =
554 );
Derek Jones4b9c6292011-07-01 17:40:48 -0500555
Derek Jones2ef37592010-10-06 17:51:59 -0500556 if ( ! $relative_path)
557 {
558 $bad[] = './';
559 $bad[] = '/';
560 }
Derek Jonese701d762010-03-02 18:17:01 -0600561
Pascal Krietec9c045a2011-04-05 14:50:41 -0400562 $str = remove_invisible_characters($str, FALSE);
Derek Jonese701d762010-03-02 18:17:01 -0600563 return stripslashes(str_replace($bad, '', $str));
564 }
565
Pascal Krietec9c045a2011-04-05 14:50:41 -0400566 // ----------------------------------------------------------------
567
568 /**
569 * Compact Exploded Words
570 *
571 * Callback function for xss_clean() to remove whitespace from
572 * things like j a v a s c r i p t
573 *
574 * @param type
575 * @return type
576 */
577 protected function _compact_exploded_words($matches)
578 {
579 return preg_replace('/\s+/s', '', $matches[1]).$matches[2];
580 }
581
582 // --------------------------------------------------------------------
Derek Jones4b9c6292011-07-01 17:40:48 -0500583
Pascal Krietec9c045a2011-04-05 14:50:41 -0400584 /*
585 * Remove Evil HTML Attributes (like evenhandlers and style)
586 *
587 * It removes the evil attribute and either:
588 * - Everything up until a space
589 * For example, everything between the pipes:
590 * <a |style=document.write('hello');alert('world');| class=link>
Derek Jones4b9c6292011-07-01 17:40:48 -0500591 * - Everything inside the quotes
Pascal Krietec9c045a2011-04-05 14:50:41 -0400592 * For example, everything between the pipes:
593 * <a |style="document.write('hello'); alert('world');"| class="link">
594 *
595 * @param string $str The string to check
596 * @param boolean $is_image TRUE if this is an image
597 * @return string The string with the evil attributes removed
598 */
599 protected function _remove_evil_attributes($str, $is_image)
600 {
601 // All javascript event handlers (e.g. onload, onclick, onmouseover), style, and xmlns
602 $evil_attributes = array('on\w*', 'style', 'xmlns');
603
604 if ($is_image === TRUE)
605 {
606 /*
Derek Jones4b9c6292011-07-01 17:40:48 -0500607 * Adobe Photoshop puts XML metadata into JFIF images,
Pascal Krietec9c045a2011-04-05 14:50:41 -0400608 * including namespacing, so we have to allow this for images.
609 */
610 unset($evil_attributes[array_search('xmlns', $evil_attributes)]);
611 }
Derek Jones4b9c6292011-07-01 17:40:48 -0500612
Pascal Krietec9c045a2011-04-05 14:50:41 -0400613 do {
614 $str = preg_replace(
615 "#<(/?[^><]+?)([^A-Za-z\-])(".implode('|', $evil_attributes).")(\s*=\s*)([\"][^>]*?[\"]|[\'][^>]*?[\']|[^>]*?)([\s><])([><]*)#i",
616 "<$1$6",
617 $str, -1, $count
618 );
619 } while ($count);
Derek Jones4b9c6292011-07-01 17:40:48 -0500620
Pascal Krietec9c045a2011-04-05 14:50:41 -0400621 return $str;
622 }
Derek Jones4b9c6292011-07-01 17:40:48 -0500623
Pascal Krietec9c045a2011-04-05 14:50:41 -0400624 // --------------------------------------------------------------------
625
626 /**
627 * Sanitize Naughty HTML
628 *
629 * Callback function for xss_clean() to remove naughty HTML elements
630 *
631 * @param array
632 * @return string
633 */
634 protected function _sanitize_naughty_html($matches)
635 {
636 // encode opening brace
637 $str = '&lt;'.$matches[1].$matches[2].$matches[3];
638
639 // encode captured opening or closing brace to prevent recursive vectors
Derek Jones4b9c6292011-07-01 17:40:48 -0500640 $str .= str_replace(array('>', '<'), array('&gt;', '&lt;'),
Pascal Krietec9c045a2011-04-05 14:50:41 -0400641 $matches[4]);
642
643 return $str;
644 }
645
646 // --------------------------------------------------------------------
647
648 /**
649 * JS Link Removal
650 *
651 * Callback function for xss_clean() to sanitize links
652 * This limits the PCRE backtracks, making it more performance friendly
653 * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in
654 * PHP 5.2+ on link-heavy strings
655 *
656 * @param array
657 * @return string
658 */
659 protected function _js_link_removal($match)
660 {
661 $attributes = $this->_filter_attributes(str_replace(array('<', '>'), '', $match[1]));
Derek Jones4b9c6292011-07-01 17:40:48 -0500662
Pascal Krietec9c045a2011-04-05 14:50:41 -0400663 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]);
664 }
665
666 // --------------------------------------------------------------------
667
668 /**
669 * JS Image Removal
670 *
671 * Callback function for xss_clean() to sanitize image tags
672 * This limits the PCRE backtracks, making it more performance friendly
673 * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in
674 * PHP 5.2+ on image tag heavy strings
675 *
676 * @param array
677 * @return string
678 */
679 protected function _js_img_removal($match)
680 {
681 $attributes = $this->_filter_attributes(str_replace(array('<', '>'), '', $match[1]));
Derek Jones4b9c6292011-07-01 17:40:48 -0500682
Pascal Krietec9c045a2011-04-05 14:50:41 -0400683 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]);
684 }
685
686 // --------------------------------------------------------------------
687
688 /**
689 * Attribute Conversion
690 *
691 * Used as a callback for XSS Clean
692 *
693 * @param array
694 * @return string
695 */
696 protected function _convert_attribute($match)
697 {
698 return str_replace(array('>', '<', '\\'), array('&gt;', '&lt;', '\\\\'), $match[0]);
699 }
700
701 // --------------------------------------------------------------------
702
703 /**
704 * Filter Attributes
705 *
706 * Filters tag attributes for consistency and safety
707 *
708 * @param string
709 * @return string
710 */
711 protected function _filter_attributes($str)
712 {
713 $out = '';
714
715 if (preg_match_all('#\s*[a-z\-]+\s*=\s*(\042|\047)([^\\1]*?)\\1#is', $str, $matches))
716 {
717 foreach ($matches[0] as $match)
718 {
719 $out .= preg_replace("#/\*.*?\*/#s", '', $match);
720 }
721 }
722
723 return $out;
724 }
725
726 // --------------------------------------------------------------------
727
728 /**
729 * HTML Entity Decode Callback
730 *
731 * Used as a callback for XSS Clean
732 *
733 * @param array
734 * @return string
735 */
736 protected function _decode_entity($match)
737 {
738 return $this->entity_decode($match[0], strtoupper(config_item('charset')));
739 }
740
741 // --------------------------------------------------------------------
Derek Jones4b9c6292011-07-01 17:40:48 -0500742
Pascal Krietec9c045a2011-04-05 14:50:41 -0400743 /**
744 * Validate URL entities
745 *
746 * Called by xss_clean()
747 *
Derek Jones4b9c6292011-07-01 17:40:48 -0500748 * @param string
Pascal Krietec9c045a2011-04-05 14:50:41 -0400749 * @return string
750 */
751 protected function _validate_entities($str)
752 {
753 /*
754 * Protect GET variables in URLs
755 */
Derek Jones4b9c6292011-07-01 17:40:48 -0500756
Pascal Krietec9c045a2011-04-05 14:50:41 -0400757 // 901119URL5918AMP18930PROTECT8198
Derek Jones4b9c6292011-07-01 17:40:48 -0500758
Pascal Krietec9c045a2011-04-05 14:50:41 -0400759 $str = preg_replace('|\&([a-z\_0-9\-]+)\=([a-z\_0-9\-]+)|i', $this->xss_hash()."\\1=\\2", $str);
760
761 /*
762 * Validate standard character entities
763 *
Derek Jones4b9c6292011-07-01 17:40:48 -0500764 * Add a semicolon if missing. We do this to enable
Pascal Krietec9c045a2011-04-05 14:50:41 -0400765 * the conversion of entities to ASCII later.
766 *
767 */
768 $str = preg_replace('#(&\#?[0-9a-z]{2,})([\x00-\x20])*;?#i', "\\1;\\2", $str);
769
770 /*
771 * Validate UTF16 two byte encoding (x00)
772 *
773 * Just as above, adds a semicolon if missing.
774 *
775 */
776 $str = preg_replace('#(&\#x?)([0-9A-F]+);?#i',"\\1\\2;",$str);
777
778 /*
779 * Un-Protect GET variables in URLs
780 */
781 $str = str_replace($this->xss_hash(), '&', $str);
Derek Jones4b9c6292011-07-01 17:40:48 -0500782
Pascal Krietec9c045a2011-04-05 14:50:41 -0400783 return $str;
784 }
785
786 // ----------------------------------------------------------------------
787
788 /**
789 * Do Never Allowed
790 *
791 * A utility function for xss_clean()
792 *
793 * @param string
794 * @return string
795 */
796 protected function _do_never_allowed($str)
797 {
798 foreach ($this->_never_allowed_str as $key => $val)
799 {
800 $str = str_replace($key, $val, $str);
801 }
802
803 foreach ($this->_never_allowed_regex as $key => $val)
804 {
805 $str = preg_replace("#".$key."#i", $val, $str);
806 }
Derek Jones4b9c6292011-07-01 17:40:48 -0500807
Pascal Krietec9c045a2011-04-05 14:50:41 -0400808 return $str;
809 }
810
811 // --------------------------------------------------------------------
812
813 /**
814 * Set Cross Site Request Forgery Protection Cookie
815 *
816 * @return string
817 */
818 protected function _csrf_set_hash()
819 {
820 if ($this->_csrf_hash == '')
821 {
Derek Jones4b9c6292011-07-01 17:40:48 -0500822 // If the cookie exists we will use it's value.
Pascal Krietec9c045a2011-04-05 14:50:41 -0400823 // We don't necessarily want to regenerate it with
Derek Jones4b9c6292011-07-01 17:40:48 -0500824 // each page load since a page could contain embedded
Pascal Krietec9c045a2011-04-05 14:50:41 -0400825 // sub-pages causing this feature to fail
Derek Jones4b9c6292011-07-01 17:40:48 -0500826 if (isset($_COOKIE[$this->_csrf_cookie_name]) &&
Pascal Krietec9c045a2011-04-05 14:50:41 -0400827 $_COOKIE[$this->_csrf_cookie_name] != '')
828 {
829 return $this->_csrf_hash = $_COOKIE[$this->_csrf_cookie_name];
830 }
Derek Jones4b9c6292011-07-01 17:40:48 -0500831
Pascal Krietec9c045a2011-04-05 14:50:41 -0400832 return $this->_csrf_hash = md5(uniqid(rand(), TRUE));
833 }
834
835 return $this->_csrf_hash;
836 }
837
Derek Jonese701d762010-03-02 18:17:01 -0600838}
839// END Security Class
840
841/* End of file Security.php */
patworkef1a55a2011-04-09 13:04:06 +0200842/* Location: ./system/libraries/Security.php */