blob: dcc680a1167613ebf49e08078189ada35c939314 [file] [log] [blame]
Derek Jones37f4b9c2011-07-01 17:56:50 -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 {
Barry Mienydd671972010-10-04 16:33:58 +020028
David Behler07b53422011-08-15 00:25:06 +020029 /**
30 * Random Hash for protecting URLs
31 *
32 * @var string
33 * @access protected
34 */
35 protected $_xss_hash = '';
36 /**
37 * Random Hash for Cross Site Request Forgery Protection Cookie
38 *
39 * @var string
40 * @access protected
41 */
42 protected $_csrf_hash = '';
43 /**
44 * Expiration time for Cross Site Request Forgery Protection Cookie
45 * Defaults to two hours (in seconds)
46 *
47 * @var int
48 * @access protected
49 */
50 protected $_csrf_expire = 7200;
51 /**
52 * Token name for Cross Site Request Forgery Protection Cookie
53 *
54 * @var string
55 * @access protected
56 */
57 protected $_csrf_token_name = 'ci_csrf_token';
58 /**
59 * Cookie name for Cross Site Request Forgery Protection Cookie
60 *
61 * @var string
62 * @access protected
63 */
64 protected $_csrf_cookie_name = 'ci_csrf_token';
65 /**
66 * List of never allowed strings
67 *
68 * @var array
69 * @access protected
70 */
Pascal Krietec9c045a2011-04-05 14:50:41 -040071 protected $_never_allowed_str = array(
72 'document.cookie' => '[removed]',
73 'document.write' => '[removed]',
74 '.parentNode' => '[removed]',
75 '.innerHTML' => '[removed]',
76 'window.location' => '[removed]',
77 '-moz-binding' => '[removed]',
78 '<!--' => '&lt;!--',
79 '-->' => '--&gt;',
80 '<![CDATA[' => '&lt;![CDATA['
81 );
Derek Jonese701d762010-03-02 18:17:01 -060082
Pascal Krietec9c045a2011-04-05 14:50:41 -040083 /* never allowed, regex replacement */
David Behler07b53422011-08-15 00:25:06 +020084 /**
85 * List of never allowed regex replacement
86 *
87 * @var array
88 * @access protected
89 */
Pascal Krietec9c045a2011-04-05 14:50:41 -040090 protected $_never_allowed_regex = array(
91 "javascript\s*:" => '[removed]',
92 "expression\s*(\(|&\#40;)" => '[removed]', // CSS and IE
93 "vbscript\s*:" => '[removed]', // IE, surprise!
94 "Redirect\s+302" => '[removed]'
95 );
David Behler07b53422011-08-15 00:25:06 +020096
Pascal Krietec9c045a2011-04-05 14:50:41 -040097 /**
98 * Constructor
99 */
Greg Akera9263282010-11-10 15:26:43 -0600100 public function __construct()
Derek Jonese701d762010-03-02 18:17:01 -0600101 {
patworkef1a55a2011-04-09 13:04:06 +0200102 // CSRF config
103 foreach(array('csrf_expire', 'csrf_token_name', 'csrf_cookie_name') as $key)
104 {
105 if (FALSE !== ($val = config_item($key)))
106 {
107 $this->{'_'.$key} = $val;
108 }
109 }
110
patwork9e267982011-04-11 13:02:32 +0200111 // Append application specific cookie prefix
Greg Akerb3e614d2011-04-19 20:19:17 -0500112 if (config_item('cookie_prefix'))
113 {
patwork9e267982011-04-11 13:02:32 +0200114 $this->_csrf_cookie_name = config_item('cookie_prefix').$this->_csrf_cookie_name;
115 }
Derek Jonesb3f10a22010-07-25 19:11:26 -0500116
Derek Jonese701d762010-03-02 18:17:01 -0600117 // Set the CSRF hash
118 $this->_csrf_set_hash();
Derek Allard958543a2010-07-22 14:10:26 -0400119
Derek Jonese701d762010-03-02 18:17:01 -0600120 log_message('debug', "Security Class Initialized");
121 }
122
123 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200124
Derek Jonese701d762010-03-02 18:17:01 -0600125 /**
126 * Verify Cross Site Request Forgery Protection
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_verify()
Derek Allard958543a2010-07-22 14:10:26 -0400131 {
Derek Jonese701d762010-03-02 18:17:01 -0600132 // If no POST data exists we will set the CSRF cookie
133 if (count($_POST) == 0)
134 {
135 return $this->csrf_set_cookie();
136 }
137
138 // Do the tokens exist in both the _POST and _COOKIE arrays?
David Behler07b53422011-08-15 00:25:06 +0200139 if ( ! isset($_POST[$this->_csrf_token_name]) OR
Pascal Krietec9c045a2011-04-05 14:50:41 -0400140 ! isset($_COOKIE[$this->_csrf_cookie_name]))
Derek Jonese701d762010-03-02 18:17:01 -0600141 {
142 $this->csrf_show_error();
143 }
144
145 // Do the tokens match?
Pascal Krietec9c045a2011-04-05 14:50:41 -0400146 if ($_POST[$this->_csrf_token_name] != $_COOKIE[$this->_csrf_cookie_name])
Derek Jonese701d762010-03-02 18:17:01 -0600147 {
148 $this->csrf_show_error();
149 }
150
David Behler07b53422011-08-15 00:25:06 +0200151 // We kill this since we're done and we don't want to
Pascal Krietec9c045a2011-04-05 14:50:41 -0400152 // polute the _POST array
153 unset($_POST[$this->_csrf_token_name]);
Barry Mienydd671972010-10-04 16:33:58 +0200154
Derek Jonesb3f10a22010-07-25 19:11:26 -0500155 // Nothing should last forever
Pascal Krietec9c045a2011-04-05 14:50:41 -0400156 unset($_COOKIE[$this->_csrf_cookie_name]);
Derek Jonesb3f10a22010-07-25 19:11:26 -0500157 $this->_csrf_set_hash();
158 $this->csrf_set_cookie();
Derek Jonese701d762010-03-02 18:17:01 -0600159
160 log_message('debug', "CSRF token verified ");
David Behler07b53422011-08-15 00:25:06 +0200161
Pascal Krietec9c045a2011-04-05 14:50:41 -0400162 return $this;
Derek Jonese701d762010-03-02 18:17:01 -0600163 }
Barry Mienydd671972010-10-04 16:33:58 +0200164
Derek Jonese701d762010-03-02 18:17:01 -0600165 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200166
Derek Jonese701d762010-03-02 18:17:01 -0600167 /**
168 * Set Cross Site Request Forgery Protection Cookie
169 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400170 * @return object
Derek Jonese701d762010-03-02 18:17:01 -0600171 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500172 public function csrf_set_cookie()
Derek Jonese701d762010-03-02 18:17:01 -0600173 {
Pascal Krietec9c045a2011-04-05 14:50:41 -0400174 $expire = time() + $this->_csrf_expire;
Robin Sowell154da112011-02-11 15:33:44 -0500175 $secure_cookie = (config_item('cookie_secure') === TRUE) ? 1 : 0;
Derek Jonese701d762010-03-02 18:17:01 -0600176
Pascal Krietec9c045a2011-04-05 14:50:41 -0400177 if ($secure_cookie)
Derek Jonese701d762010-03-02 18:17:01 -0600178 {
Pascal Krietec9c045a2011-04-05 14:50:41 -0400179 $req = isset($_SERVER['HTTPS']) ? $_SERVER['HTTPS'] : FALSE;
180
181 if ( ! $req OR $req == 'off')
Derek Jonese701d762010-03-02 18:17:01 -0600182 {
Pascal Krietec9c045a2011-04-05 14:50:41 -0400183 return FALSE;
Derek Jonese701d762010-03-02 18:17:01 -0600184 }
185 }
Derek Allard958543a2010-07-22 14:10:26 -0400186
Pascal Krietec9c045a2011-04-05 14:50:41 -0400187 setcookie($this->_csrf_cookie_name, $this->_csrf_hash, $expire, config_item('cookie_path'), config_item('cookie_domain'), $secure_cookie);
188
189 log_message('debug', "CRSF cookie Set");
David Behler07b53422011-08-15 00:25:06 +0200190
Pascal Krietec9c045a2011-04-05 14:50:41 -0400191 return $this;
Derek Jonese701d762010-03-02 18:17:01 -0600192 }
193
194 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200195
Derek Jonese701d762010-03-02 18:17:01 -0600196 /**
197 * Show CSRF Error
198 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400199 * @return void
Derek Jonese701d762010-03-02 18:17:01 -0600200 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500201 public function csrf_show_error()
Derek Jonese701d762010-03-02 18:17:01 -0600202 {
203 show_error('The action you have requested is not allowed.');
204 }
205
206 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200207
Derek Jonese701d762010-03-02 18:17:01 -0600208 /**
David Behler07b53422011-08-15 00:25:06 +0200209 * Get CSRF Hash
Pascal Krietec9c045a2011-04-05 14:50:41 -0400210 *
David Behler07b53422011-08-15 00:25:06 +0200211 * Getter Method
Pascal Krietec9c045a2011-04-05 14:50:41 -0400212 *
213 * @return string self::_csrf_hash
214 */
215 public function get_csrf_hash()
216 {
217 return $this->_csrf_hash;
218 }
219
220 // --------------------------------------------------------------------
221
222 /**
223 * Get CSRF Token Name
224 *
225 * Getter Method
226 *
227 * @return string self::csrf_token_name
228 */
229 public function get_csrf_token_name()
230 {
231 return $this->_csrf_token_name;
232 }
233
234 // --------------------------------------------------------------------
235
236 /**
Derek Jonese701d762010-03-02 18:17:01 -0600237 * XSS Clean
238 *
239 * Sanitizes data so that Cross Site Scripting Hacks can be
Derek Jones37f4b9c2011-07-01 17:56:50 -0500240 * prevented. This function does a fair amount of work but
Derek Jonese701d762010-03-02 18:17:01 -0600241 * it is extremely thorough, designed to prevent even the
Derek Jones37f4b9c2011-07-01 17:56:50 -0500242 * most obscure XSS attempts. Nothing is ever 100% foolproof,
Derek Jonese701d762010-03-02 18:17:01 -0600243 * of course, but I haven't been able to get anything passed
244 * the filter.
245 *
246 * Note: This function should only be used to deal with data
Derek Jones37f4b9c2011-07-01 17:56:50 -0500247 * upon submission. It's not something that should
Derek Jonese701d762010-03-02 18:17:01 -0600248 * be used for general runtime processing.
249 *
250 * This function was based in part on some code and ideas I
251 * got from Bitflux: http://channel.bitflux.ch/wiki/XSS_Prevention
252 *
253 * To help develop this script I used this great list of
254 * vulnerabilities along with a few other hacks I've
255 * harvested from examining vulnerabilities in other programs:
256 * http://ha.ckers.org/xss.html
257 *
Derek Jonese701d762010-03-02 18:17:01 -0600258 * @param mixed string or array
David Behler07b53422011-08-15 00:25:06 +0200259 * @param bool
Derek Jonese701d762010-03-02 18:17:01 -0600260 * @return string
261 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500262 public function xss_clean($str, $is_image = FALSE)
Derek Jonese701d762010-03-02 18:17:01 -0600263 {
264 /*
265 * Is the string an array?
266 *
267 */
268 if (is_array($str))
269 {
270 while (list($key) = each($str))
271 {
272 $str[$key] = $this->xss_clean($str[$key]);
273 }
Barry Mienydd671972010-10-04 16:33:58 +0200274
Derek Jonese701d762010-03-02 18:17:01 -0600275 return $str;
276 }
277
278 /*
279 * Remove Invisible Characters
280 */
Greg Aker757dda62010-04-14 19:06:19 -0500281 $str = remove_invisible_characters($str);
Derek Jonese701d762010-03-02 18:17:01 -0600282
Pascal Krietec9c045a2011-04-05 14:50:41 -0400283 // Validate Entities in URLs
284 $str = $this->_validate_entities($str);
Derek Jonese701d762010-03-02 18:17:01 -0600285
286 /*
287 * URL Decode
288 *
289 * Just in case stuff like this is submitted:
290 *
291 * <a href="http://%77%77%77%2E%67%6F%6F%67%6C%65%2E%63%6F%6D">Google</a>
292 *
293 * Note: Use rawurldecode() so it does not remove plus signs
294 *
295 */
296 $str = rawurldecode($str);
Barry Mienydd671972010-10-04 16:33:58 +0200297
Derek Jonese701d762010-03-02 18:17:01 -0600298 /*
Barry Mienydd671972010-10-04 16:33:58 +0200299 * Convert character entities to ASCII
Derek Jonese701d762010-03-02 18:17:01 -0600300 *
301 * This permits our tests below to work reliably.
302 * We only convert entities that are within tags since
303 * these are the ones that will pose security problems.
304 *
305 */
306
307 $str = preg_replace_callback("/[a-z]+=([\'\"]).*?\\1/si", array($this, '_convert_attribute'), $str);
David Behler07b53422011-08-15 00:25:06 +0200308
Derek Jonese701d762010-03-02 18:17:01 -0600309 $str = preg_replace_callback("/<\w+.*?(?=>|<|$)/si", array($this, '_decode_entity'), $str);
310
311 /*
312 * Remove Invisible Characters Again!
313 */
Greg Aker757dda62010-04-14 19:06:19 -0500314 $str = remove_invisible_characters($str);
Barry Mienydd671972010-10-04 16:33:58 +0200315
Derek Jonese701d762010-03-02 18:17:01 -0600316 /*
317 * Convert all tabs to spaces
318 *
319 * This prevents strings like this: ja vascript
320 * NOTE: we deal with spaces between characters later.
David Behler07b53422011-08-15 00:25:06 +0200321 * NOTE: preg_replace was found to be amazingly slow here on
Pascal Krietec9c045a2011-04-05 14:50:41 -0400322 * large blocks of data, so we use str_replace.
Derek Jonese701d762010-03-02 18:17:01 -0600323 */
Barry Mienydd671972010-10-04 16:33:58 +0200324
Derek Jonese701d762010-03-02 18:17:01 -0600325 if (strpos($str, "\t") !== FALSE)
326 {
327 $str = str_replace("\t", ' ', $str);
328 }
Barry Mienydd671972010-10-04 16:33:58 +0200329
Derek Jonese701d762010-03-02 18:17:01 -0600330 /*
331 * Capture converted string for later comparison
332 */
333 $converted_string = $str;
Barry Mienydd671972010-10-04 16:33:58 +0200334
Pascal Krietec9c045a2011-04-05 14:50:41 -0400335 // Remove Strings that are never allowed
336 $str = $this->_do_never_allowed($str);
Derek Jonese701d762010-03-02 18:17:01 -0600337
338 /*
339 * Makes PHP tags safe
340 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400341 * Note: XML tags are inadvertently replaced too:
Derek Jonese701d762010-03-02 18:17:01 -0600342 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400343 * <?xml
Derek Jonese701d762010-03-02 18:17:01 -0600344 *
345 * But it doesn't seem to pose a problem.
Derek Jonese701d762010-03-02 18:17:01 -0600346 */
347 if ($is_image === TRUE)
348 {
David Behler07b53422011-08-15 00:25:06 +0200349 // Images have a tendency to have the PHP short opening and
350 // closing tags every so often so we skip those and only
Pascal Krietec9c045a2011-04-05 14:50:41 -0400351 // do the long opening tags.
Derek Jonese701d762010-03-02 18:17:01 -0600352 $str = preg_replace('/<\?(php)/i', "&lt;?\\1", $str);
353 }
354 else
355 {
Derek Jones37f4b9c2011-07-01 17:56:50 -0500356 $str = str_replace(array('<?', '?'.'>'), array('&lt;?', '?&gt;'), $str);
Derek Jonese701d762010-03-02 18:17:01 -0600357 }
Barry Mienydd671972010-10-04 16:33:58 +0200358
Derek Jonese701d762010-03-02 18:17:01 -0600359 /*
360 * Compact any exploded words
361 *
Derek Jones37f4b9c2011-07-01 17:56:50 -0500362 * This corrects words like: j a v a s c r i p t
Derek Jonese701d762010-03-02 18:17:01 -0600363 * These words are compacted back to their correct state.
Derek Jonese701d762010-03-02 18:17:01 -0600364 */
Pascal Krietec9c045a2011-04-05 14:50:41 -0400365 $words = array(
David Behler07b53422011-08-15 00:25:06 +0200366 'javascript', 'expression', 'vbscript', 'script',
Pascal Krietec9c045a2011-04-05 14:50:41 -0400367 'applet', 'alert', 'document', 'write', 'cookie', 'window'
368 );
David Behler07b53422011-08-15 00:25:06 +0200369
Derek Jonese701d762010-03-02 18:17:01 -0600370 foreach ($words as $word)
371 {
372 $temp = '';
Barry Mienydd671972010-10-04 16:33:58 +0200373
Derek Jonese701d762010-03-02 18:17:01 -0600374 for ($i = 0, $wordlen = strlen($word); $i < $wordlen; $i++)
375 {
376 $temp .= substr($word, $i, 1)."\s*";
377 }
378
379 // We only want to do this when it is followed by a non-word character
380 // That way valid stuff like "dealer to" does not become "dealerto"
381 $str = preg_replace_callback('#('.substr($temp, 0, -3).')(\W)#is', array($this, '_compact_exploded_words'), $str);
382 }
Barry Mienydd671972010-10-04 16:33:58 +0200383
Derek Jonese701d762010-03-02 18:17:01 -0600384 /*
385 * Remove disallowed Javascript in links or img tags
David Behler07b53422011-08-15 00:25:06 +0200386 * We used to do some version comparisons and use of stripos for PHP5,
387 * but it is dog slow compared to these simplified non-capturing
Pascal Krietec9c045a2011-04-05 14:50:41 -0400388 * preg_match(), especially if the pattern exists in the string
Derek Jonese701d762010-03-02 18:17:01 -0600389 */
390 do
391 {
392 $original = $str;
Barry Mienydd671972010-10-04 16:33:58 +0200393
Derek Jonese701d762010-03-02 18:17:01 -0600394 if (preg_match("/<a/i", $str))
395 {
396 $str = preg_replace_callback("#<a\s+([^>]*?)(>|$)#si", array($this, '_js_link_removal'), $str);
397 }
Barry Mienydd671972010-10-04 16:33:58 +0200398
Derek Jonese701d762010-03-02 18:17:01 -0600399 if (preg_match("/<img/i", $str))
400 {
401 $str = preg_replace_callback("#<img\s+([^>]*?)(\s?/?>|$)#si", array($this, '_js_img_removal'), $str);
402 }
Barry Mienydd671972010-10-04 16:33:58 +0200403
Derek Jonese701d762010-03-02 18:17:01 -0600404 if (preg_match("/script/i", $str) OR preg_match("/xss/i", $str))
405 {
406 $str = preg_replace("#<(/*)(script|xss)(.*?)\>#si", '[removed]', $str);
407 }
408 }
Pascal Krietec9c045a2011-04-05 14:50:41 -0400409 while($original != $str);
Derek Jonese701d762010-03-02 18:17:01 -0600410
411 unset($original);
412
Pascal Krietec9c045a2011-04-05 14:50:41 -0400413 // Remove evil attributes such as style, onclick and xmlns
414 $str = $this->_remove_evil_attributes($str, $is_image);
Barry Mienydd671972010-10-04 16:33:58 +0200415
Derek Jonese701d762010-03-02 18:17:01 -0600416 /*
417 * Sanitize naughty HTML elements
418 *
419 * If a tag containing any of the words in the list
420 * below is found, the tag gets converted to entities.
421 *
422 * So this: <blink>
423 * Becomes: &lt;blink&gt;
Derek Jonese701d762010-03-02 18:17:01 -0600424 */
425 $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';
426 $str = preg_replace_callback('#<(/*\s*)('.$naughty.')([^><]*)([><]*)#is', array($this, '_sanitize_naughty_html'), $str);
427
428 /*
429 * Sanitize naughty scripting elements
430 *
431 * Similar to above, only instead of looking for
432 * tags it looks for PHP and JavaScript commands
Derek Jones37f4b9c2011-07-01 17:56:50 -0500433 * that are disallowed. Rather than removing the
Derek Jonese701d762010-03-02 18:17:01 -0600434 * code, it simply converts the parenthesis to entities
435 * rendering the code un-executable.
436 *
437 * For example: eval('some code')
438 * Becomes: eval&#40;'some code'&#41;
Derek Jonese701d762010-03-02 18:17:01 -0600439 */
440 $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 +0200441
Barry Mienydd671972010-10-04 16:33:58 +0200442
Pascal Krietec9c045a2011-04-05 14:50:41 -0400443 // Final clean up
444 // This adds a bit of extra precaution in case
445 // something got through the above filters
446 $str = $this->_do_never_allowed($str);
Derek Jonese701d762010-03-02 18:17:01 -0600447
448 /*
Pascal Krietec9c045a2011-04-05 14:50:41 -0400449 * Images are Handled in a Special Way
David Behler07b53422011-08-15 00:25:06 +0200450 * - Essentially, we want to know that after all of the character
451 * conversion is done whether any unwanted, likely XSS, code was found.
Pascal Krietec9c045a2011-04-05 14:50:41 -0400452 * If not, we return TRUE, as the image is clean.
David Behler07b53422011-08-15 00:25:06 +0200453 * However, if the string post-conversion does not matched the
454 * string post-removal of XSS, then it fails, as there was unwanted XSS
Pascal Krietec9c045a2011-04-05 14:50:41 -0400455 * code found and removed/changed during processing.
Derek Jonese701d762010-03-02 18:17:01 -0600456 */
457
458 if ($is_image === TRUE)
459 {
Pascal Krietec9c045a2011-04-05 14:50:41 -0400460 return ($str == $converted_string) ? TRUE: FALSE;
Derek Jonese701d762010-03-02 18:17:01 -0600461 }
Barry Mienydd671972010-10-04 16:33:58 +0200462
Derek Jonese701d762010-03-02 18:17:01 -0600463 log_message('debug', "XSS Filtering completed");
464 return $str;
465 }
466
467 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200468
Derek Jonese701d762010-03-02 18:17:01 -0600469 /**
470 * Random Hash for protecting URLs
471 *
Derek Jonese701d762010-03-02 18:17:01 -0600472 * @return string
473 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500474 public function xss_hash()
Barry Mienydd671972010-10-04 16:33:58 +0200475 {
Pascal Krietec9c045a2011-04-05 14:50:41 -0400476 if ($this->_xss_hash == '')
Derek Jonese701d762010-03-02 18:17:01 -0600477 {
478 if (phpversion() >= 4.2)
Derek Jonese701d762010-03-02 18:17:01 -0600479 {
Pascal Krietec9c045a2011-04-05 14:50:41 -0400480 mt_srand();
Derek Jonese701d762010-03-02 18:17:01 -0600481 }
Pascal Krietec9c045a2011-04-05 14:50:41 -0400482 else
483 {
484 mt_srand(hexdec(substr(md5(microtime()), -8)) & 0x7fffffff);
485 }
486
487 $this->_xss_hash = md5(time() + mt_rand(0, 1999999999));
Derek Jonese701d762010-03-02 18:17:01 -0600488 }
489
Pascal Krietec9c045a2011-04-05 14:50:41 -0400490 return $this->_xss_hash;
Derek Jonese701d762010-03-02 18:17:01 -0600491 }
492
493 // --------------------------------------------------------------------
494
495 /**
Derek Jonesa0911472010-03-30 10:33:09 -0500496 * HTML Entities Decode
497 *
498 * This function is a replacement for html_entity_decode()
499 *
500 * In some versions of PHP the native function does not work
501 * when UTF-8 is the specified character set, so this gives us
Derek Jones37f4b9c2011-07-01 17:56:50 -0500502 * a work-around. More info here:
Derek Jonesa0911472010-03-30 10:33:09 -0500503 * http://bugs.php.net/bug.php?id=25670
504 *
505 * NOTE: html_entity_decode() has a bug in some PHP versions when UTF-8 is the
506 * character set, and the PHP developers said they were not back porting the
507 * fix to versions other than PHP 5.x.
508 *
Derek Jonesa0911472010-03-30 10:33:09 -0500509 * @param string
510 * @param string
511 * @return string
512 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500513 public function entity_decode($str, $charset='UTF-8')
Derek Jonesa0911472010-03-30 10:33:09 -0500514 {
515 if (stristr($str, '&') === FALSE) return $str;
Barry Mienydd671972010-10-04 16:33:58 +0200516
Derek Jonesa0911472010-03-30 10:33:09 -0500517 // The reason we are not using html_entity_decode() by itself is because
518 // while it is not technically correct to leave out the semicolon
519 // at the end of an entity most browsers will still interpret the entity
Derek Jones37f4b9c2011-07-01 17:56:50 -0500520 // correctly. html_entity_decode() does not convert entities without
Derek Jonesa0911472010-03-30 10:33:09 -0500521 // semicolons, so we are left with our own little solution here. Bummer.
Barry Mienydd671972010-10-04 16:33:58 +0200522
David Behler07b53422011-08-15 00:25:06 +0200523 if (function_exists('html_entity_decode') &&
Pascal Krietec9c045a2011-04-05 14:50:41 -0400524 (strtolower($charset) != 'utf-8'))
Derek Jonesa0911472010-03-30 10:33:09 -0500525 {
526 $str = html_entity_decode($str, ENT_COMPAT, $charset);
527 $str = preg_replace('~&#x(0*[0-9a-f]{2,5})~ei', 'chr(hexdec("\\1"))', $str);
528 return preg_replace('~&#([0-9]{2,4})~e', 'chr(\\1)', $str);
529 }
Barry Mienydd671972010-10-04 16:33:58 +0200530
Derek Jonesa0911472010-03-30 10:33:09 -0500531 // Numeric Entities
532 $str = preg_replace('~&#x(0*[0-9a-f]{2,5});{0,1}~ei', 'chr(hexdec("\\1"))', $str);
533 $str = preg_replace('~&#([0-9]{2,4});{0,1}~e', 'chr(\\1)', $str);
Barry Mienydd671972010-10-04 16:33:58 +0200534
Derek Jonesa0911472010-03-30 10:33:09 -0500535 // Literal Entities - Slightly slow so we do another check
536 if (stristr($str, '&') === FALSE)
537 {
538 $str = strtr($str, array_flip(get_html_translation_table(HTML_ENTITIES)));
539 }
Barry Mienydd671972010-10-04 16:33:58 +0200540
Derek Jonesa0911472010-03-30 10:33:09 -0500541 return $str;
542 }
Barry Mienydd671972010-10-04 16:33:58 +0200543
Derek Jonesa0911472010-03-30 10:33:09 -0500544 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200545
Derek Jonesa0911472010-03-30 10:33:09 -0500546 /**
Derek Jonese701d762010-03-02 18:17:01 -0600547 * Filename Security
548 *
Derek Jonese701d762010-03-02 18:17:01 -0600549 * @param string
David Behler07b53422011-08-15 00:25:06 +0200550 * @param bool
Derek Jonese701d762010-03-02 18:17:01 -0600551 * @return string
552 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500553 public function sanitize_filename($str, $relative_path = FALSE)
Derek Jonese701d762010-03-02 18:17:01 -0600554 {
555 $bad = array(
556 "../",
Derek Jonese701d762010-03-02 18:17:01 -0600557 "<!--",
558 "-->",
559 "<",
560 ">",
561 "'",
562 '"',
563 '&',
564 '$',
565 '#',
566 '{',
567 '}',
568 '[',
569 ']',
570 '=',
571 ';',
572 '?',
Derek Jonese701d762010-03-02 18:17:01 -0600573 "%20",
574 "%22",
575 "%3c", // <
Barry Mienydd671972010-10-04 16:33:58 +0200576 "%253c", // <
577 "%3e", // >
578 "%0e", // >
579 "%28", // (
580 "%29", // )
581 "%2528", // (
582 "%26", // &
583 "%24", // $
584 "%3f", // ?
585 "%3b", // ;
Derek Jonese701d762010-03-02 18:17:01 -0600586 "%3d" // =
587 );
David Behler07b53422011-08-15 00:25:06 +0200588
Derek Jones2ef37592010-10-06 17:51:59 -0500589 if ( ! $relative_path)
590 {
591 $bad[] = './';
592 $bad[] = '/';
593 }
Derek Jonese701d762010-03-02 18:17:01 -0600594
Pascal Krietec9c045a2011-04-05 14:50:41 -0400595 $str = remove_invisible_characters($str, FALSE);
Derek Jonese701d762010-03-02 18:17:01 -0600596 return stripslashes(str_replace($bad, '', $str));
597 }
598
Pascal Krietec9c045a2011-04-05 14:50:41 -0400599 // ----------------------------------------------------------------
600
601 /**
602 * Compact Exploded Words
603 *
604 * Callback function for xss_clean() to remove whitespace from
605 * things like j a v a s c r i p t
606 *
607 * @param type
608 * @return type
609 */
610 protected function _compact_exploded_words($matches)
611 {
612 return preg_replace('/\s+/s', '', $matches[1]).$matches[2];
613 }
614
615 // --------------------------------------------------------------------
David Behler07b53422011-08-15 00:25:06 +0200616
Pascal Krietec9c045a2011-04-05 14:50:41 -0400617 /*
618 * Remove Evil HTML Attributes (like evenhandlers and style)
619 *
620 * It removes the evil attribute and either:
621 * - Everything up until a space
622 * For example, everything between the pipes:
623 * <a |style=document.write('hello');alert('world');| class=link>
David Behler07b53422011-08-15 00:25:06 +0200624 * - Everything inside the quotes
Pascal Krietec9c045a2011-04-05 14:50:41 -0400625 * For example, everything between the pipes:
626 * <a |style="document.write('hello'); alert('world');"| class="link">
627 *
628 * @param string $str The string to check
629 * @param boolean $is_image TRUE if this is an image
630 * @return string The string with the evil attributes removed
631 */
632 protected function _remove_evil_attributes($str, $is_image)
633 {
634 // All javascript event handlers (e.g. onload, onclick, onmouseover), style, and xmlns
635 $evil_attributes = array('on\w*', 'style', 'xmlns');
636
637 if ($is_image === TRUE)
638 {
639 /*
David Behler07b53422011-08-15 00:25:06 +0200640 * Adobe Photoshop puts XML metadata into JFIF images,
Pascal Krietec9c045a2011-04-05 14:50:41 -0400641 * including namespacing, so we have to allow this for images.
642 */
643 unset($evil_attributes[array_search('xmlns', $evil_attributes)]);
644 }
David Behler07b53422011-08-15 00:25:06 +0200645
Pascal Krietec9c045a2011-04-05 14:50:41 -0400646 do {
647 $str = preg_replace(
648 "#<(/?[^><]+?)([^A-Za-z\-])(".implode('|', $evil_attributes).")(\s*=\s*)([\"][^>]*?[\"]|[\'][^>]*?[\']|[^>]*?)([\s><])([><]*)#i",
649 "<$1$6",
650 $str, -1, $count
651 );
652 } while ($count);
David Behler07b53422011-08-15 00:25:06 +0200653
Pascal Krietec9c045a2011-04-05 14:50:41 -0400654 return $str;
655 }
David Behler07b53422011-08-15 00:25:06 +0200656
Pascal Krietec9c045a2011-04-05 14:50:41 -0400657 // --------------------------------------------------------------------
658
659 /**
660 * Sanitize Naughty HTML
661 *
662 * Callback function for xss_clean() to remove naughty HTML elements
663 *
664 * @param array
665 * @return string
666 */
667 protected function _sanitize_naughty_html($matches)
668 {
669 // encode opening brace
670 $str = '&lt;'.$matches[1].$matches[2].$matches[3];
671
672 // encode captured opening or closing brace to prevent recursive vectors
David Behler07b53422011-08-15 00:25:06 +0200673 $str .= str_replace(array('>', '<'), array('&gt;', '&lt;'),
Pascal Krietec9c045a2011-04-05 14:50:41 -0400674 $matches[4]);
675
676 return $str;
677 }
678
679 // --------------------------------------------------------------------
680
681 /**
682 * JS Link Removal
683 *
684 * Callback function for xss_clean() to sanitize links
685 * This limits the PCRE backtracks, making it more performance friendly
686 * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in
687 * PHP 5.2+ on link-heavy strings
688 *
689 * @param array
690 * @return string
691 */
692 protected function _js_link_removal($match)
693 {
694 $attributes = $this->_filter_attributes(str_replace(array('<', '>'), '', $match[1]));
David Behler07b53422011-08-15 00:25:06 +0200695
Pascal Krietec9c045a2011-04-05 14:50:41 -0400696 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]);
697 }
698
699 // --------------------------------------------------------------------
700
701 /**
702 * JS Image Removal
703 *
704 * Callback function for xss_clean() to sanitize image tags
705 * This limits the PCRE backtracks, making it more performance friendly
706 * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in
707 * PHP 5.2+ on image tag heavy strings
708 *
709 * @param array
710 * @return string
711 */
712 protected function _js_img_removal($match)
713 {
714 $attributes = $this->_filter_attributes(str_replace(array('<', '>'), '', $match[1]));
David Behler07b53422011-08-15 00:25:06 +0200715
Pascal Krietec9c045a2011-04-05 14:50:41 -0400716 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]);
717 }
718
719 // --------------------------------------------------------------------
720
721 /**
722 * Attribute Conversion
723 *
724 * Used as a callback for XSS Clean
725 *
726 * @param array
727 * @return string
728 */
729 protected function _convert_attribute($match)
730 {
731 return str_replace(array('>', '<', '\\'), array('&gt;', '&lt;', '\\\\'), $match[0]);
732 }
733
734 // --------------------------------------------------------------------
735
736 /**
737 * Filter Attributes
738 *
739 * Filters tag attributes for consistency and safety
740 *
741 * @param string
742 * @return string
743 */
744 protected function _filter_attributes($str)
745 {
746 $out = '';
747
748 if (preg_match_all('#\s*[a-z\-]+\s*=\s*(\042|\047)([^\\1]*?)\\1#is', $str, $matches))
749 {
750 foreach ($matches[0] as $match)
751 {
752 $out .= preg_replace("#/\*.*?\*/#s", '', $match);
753 }
754 }
755
756 return $out;
757 }
758
759 // --------------------------------------------------------------------
760
761 /**
762 * HTML Entity Decode Callback
763 *
764 * Used as a callback for XSS Clean
765 *
766 * @param array
767 * @return string
768 */
769 protected function _decode_entity($match)
770 {
771 return $this->entity_decode($match[0], strtoupper(config_item('charset')));
772 }
773
774 // --------------------------------------------------------------------
David Behler07b53422011-08-15 00:25:06 +0200775
Pascal Krietec9c045a2011-04-05 14:50:41 -0400776 /**
777 * Validate URL entities
778 *
779 * Called by xss_clean()
780 *
David Behler07b53422011-08-15 00:25:06 +0200781 * @param string
Pascal Krietec9c045a2011-04-05 14:50:41 -0400782 * @return string
783 */
784 protected function _validate_entities($str)
785 {
786 /*
787 * Protect GET variables in URLs
788 */
David Behler07b53422011-08-15 00:25:06 +0200789
Pascal Krietec9c045a2011-04-05 14:50:41 -0400790 // 901119URL5918AMP18930PROTECT8198
David Behler07b53422011-08-15 00:25:06 +0200791
Pascal Krietec9c045a2011-04-05 14:50:41 -0400792 $str = preg_replace('|\&([a-z\_0-9\-]+)\=([a-z\_0-9\-]+)|i', $this->xss_hash()."\\1=\\2", $str);
793
794 /*
795 * Validate standard character entities
796 *
Derek Jones37f4b9c2011-07-01 17:56:50 -0500797 * Add a semicolon if missing. We do this to enable
Pascal Krietec9c045a2011-04-05 14:50:41 -0400798 * the conversion of entities to ASCII later.
799 *
800 */
801 $str = preg_replace('#(&\#?[0-9a-z]{2,})([\x00-\x20])*;?#i', "\\1;\\2", $str);
802
803 /*
804 * Validate UTF16 two byte encoding (x00)
805 *
806 * Just as above, adds a semicolon if missing.
807 *
808 */
809 $str = preg_replace('#(&\#x?)([0-9A-F]+);?#i',"\\1\\2;",$str);
810
811 /*
812 * Un-Protect GET variables in URLs
813 */
814 $str = str_replace($this->xss_hash(), '&', $str);
David Behler07b53422011-08-15 00:25:06 +0200815
Pascal Krietec9c045a2011-04-05 14:50:41 -0400816 return $str;
817 }
818
819 // ----------------------------------------------------------------------
820
821 /**
822 * Do Never Allowed
823 *
824 * A utility function for xss_clean()
825 *
826 * @param string
827 * @return string
828 */
829 protected function _do_never_allowed($str)
830 {
831 foreach ($this->_never_allowed_str as $key => $val)
832 {
833 $str = str_replace($key, $val, $str);
834 }
835
836 foreach ($this->_never_allowed_regex as $key => $val)
837 {
838 $str = preg_replace("#".$key."#i", $val, $str);
839 }
David Behler07b53422011-08-15 00:25:06 +0200840
Pascal Krietec9c045a2011-04-05 14:50:41 -0400841 return $str;
842 }
843
844 // --------------------------------------------------------------------
845
846 /**
847 * Set Cross Site Request Forgery Protection Cookie
848 *
849 * @return string
850 */
851 protected function _csrf_set_hash()
852 {
853 if ($this->_csrf_hash == '')
854 {
David Behler07b53422011-08-15 00:25:06 +0200855 // If the cookie exists we will use it's value.
Pascal Krietec9c045a2011-04-05 14:50:41 -0400856 // We don't necessarily want to regenerate it with
David Behler07b53422011-08-15 00:25:06 +0200857 // each page load since a page could contain embedded
Pascal Krietec9c045a2011-04-05 14:50:41 -0400858 // sub-pages causing this feature to fail
David Behler07b53422011-08-15 00:25:06 +0200859 if (isset($_COOKIE[$this->_csrf_cookie_name]) &&
Pascal Krietec9c045a2011-04-05 14:50:41 -0400860 $_COOKIE[$this->_csrf_cookie_name] != '')
861 {
862 return $this->_csrf_hash = $_COOKIE[$this->_csrf_cookie_name];
863 }
David Behler07b53422011-08-15 00:25:06 +0200864
Pascal Krietec9c045a2011-04-05 14:50:41 -0400865 return $this->_csrf_hash = md5(uniqid(rand(), TRUE));
866 }
867
868 return $this->_csrf_hash;
869 }
870
Derek Jonese701d762010-03-02 18:17:01 -0600871}
872// END Security Class
873
874/* End of file Security.php */
patworkef1a55a2011-04-09 13:04:06 +0200875/* Location: ./system/libraries/Security.php */