blob: 3617cadccff1903d569400121db14b2f886472d8 [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 {
Derek Jones37f4b9c2011-07-01 17:56:50 -050028
Pascal Krietec9c045a2011-04-05 14:50:41 -040029 protected $_xss_hash = '';
30 protected $_csrf_hash = '';
Derek Jones37f4b9c2011-07-01 17:56:50 -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 Jones37f4b9c2011-07-01 17:56:50 -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 }
96
97 // Do the tokens exist in both the _POST and _COOKIE arrays?
Derek Jones37f4b9c2011-07-01 17:56:50 -050098 if ( ! isset($_POST[$this->_csrf_token_name]) OR
Pascal Krietec9c045a2011-04-05 14:50:41 -040099 ! isset($_COOKIE[$this->_csrf_cookie_name]))
Derek Jonese701d762010-03-02 18:17:01 -0600100 {
101 $this->csrf_show_error();
102 }
103
104 // Do the tokens match?
Pascal Krietec9c045a2011-04-05 14:50:41 -0400105 if ($_POST[$this->_csrf_token_name] != $_COOKIE[$this->_csrf_cookie_name])
Derek Jonese701d762010-03-02 18:17:01 -0600106 {
107 $this->csrf_show_error();
108 }
109
Derek Jones37f4b9c2011-07-01 17:56:50 -0500110 // We kill this since we're done and we don't want to
Pascal Krietec9c045a2011-04-05 14:50:41 -0400111 // polute the _POST array
112 unset($_POST[$this->_csrf_token_name]);
Barry Mienydd671972010-10-04 16:33:58 +0200113
Derek Jonesb3f10a22010-07-25 19:11:26 -0500114 // Nothing should last forever
Pascal Krietec9c045a2011-04-05 14:50:41 -0400115 unset($_COOKIE[$this->_csrf_cookie_name]);
Derek Jonesb3f10a22010-07-25 19:11:26 -0500116 $this->_csrf_set_hash();
117 $this->csrf_set_cookie();
Derek Jonese701d762010-03-02 18:17:01 -0600118
119 log_message('debug', "CSRF token verified ");
Derek Jones37f4b9c2011-07-01 17:56:50 -0500120
Pascal Krietec9c045a2011-04-05 14:50:41 -0400121 return $this;
Derek Jonese701d762010-03-02 18:17:01 -0600122 }
Barry Mienydd671972010-10-04 16:33:58 +0200123
Derek Jonese701d762010-03-02 18:17:01 -0600124 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200125
Derek Jonese701d762010-03-02 18:17:01 -0600126 /**
127 * Set Cross Site Request Forgery Protection Cookie
128 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400129 * @return object
Derek Jonese701d762010-03-02 18:17:01 -0600130 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500131 public function csrf_set_cookie()
Derek Jonese701d762010-03-02 18:17:01 -0600132 {
Pascal Krietec9c045a2011-04-05 14:50:41 -0400133 $expire = time() + $this->_csrf_expire;
Robin Sowell154da112011-02-11 15:33:44 -0500134 $secure_cookie = (config_item('cookie_secure') === TRUE) ? 1 : 0;
Derek Jonese701d762010-03-02 18:17:01 -0600135
Pascal Krietec9c045a2011-04-05 14:50:41 -0400136 if ($secure_cookie)
Derek Jonese701d762010-03-02 18:17:01 -0600137 {
Pascal Krietec9c045a2011-04-05 14:50:41 -0400138 $req = isset($_SERVER['HTTPS']) ? $_SERVER['HTTPS'] : FALSE;
139
140 if ( ! $req OR $req == 'off')
Derek Jonese701d762010-03-02 18:17:01 -0600141 {
Pascal Krietec9c045a2011-04-05 14:50:41 -0400142 return FALSE;
Derek Jonese701d762010-03-02 18:17:01 -0600143 }
144 }
Derek Allard958543a2010-07-22 14:10:26 -0400145
Pascal Krietec9c045a2011-04-05 14:50:41 -0400146 setcookie($this->_csrf_cookie_name, $this->_csrf_hash, $expire, config_item('cookie_path'), config_item('cookie_domain'), $secure_cookie);
147
148 log_message('debug', "CRSF cookie Set");
Derek Jones37f4b9c2011-07-01 17:56:50 -0500149
Pascal Krietec9c045a2011-04-05 14:50:41 -0400150 return $this;
Derek Jonese701d762010-03-02 18:17:01 -0600151 }
152
153 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200154
Derek Jonese701d762010-03-02 18:17:01 -0600155 /**
156 * Show CSRF Error
157 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400158 * @return void
Derek Jonese701d762010-03-02 18:17:01 -0600159 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500160 public function csrf_show_error()
Derek Jonese701d762010-03-02 18:17:01 -0600161 {
162 show_error('The action you have requested is not allowed.');
163 }
164
165 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200166
Derek Jonese701d762010-03-02 18:17:01 -0600167 /**
Derek Jones37f4b9c2011-07-01 17:56:50 -0500168 * Get CSRF Hash
Pascal Krietec9c045a2011-04-05 14:50:41 -0400169 *
Derek Jones37f4b9c2011-07-01 17:56:50 -0500170 * Getter Method
Pascal Krietec9c045a2011-04-05 14:50:41 -0400171 *
172 * @return string self::_csrf_hash
173 */
174 public function get_csrf_hash()
175 {
176 return $this->_csrf_hash;
177 }
178
179 // --------------------------------------------------------------------
180
181 /**
182 * Get CSRF Token Name
183 *
184 * Getter Method
185 *
186 * @return string self::csrf_token_name
187 */
188 public function get_csrf_token_name()
189 {
190 return $this->_csrf_token_name;
191 }
192
193 // --------------------------------------------------------------------
194
195 /**
Derek Jonese701d762010-03-02 18:17:01 -0600196 * XSS Clean
197 *
198 * Sanitizes data so that Cross Site Scripting Hacks can be
Derek Jones37f4b9c2011-07-01 17:56:50 -0500199 * prevented. This function does a fair amount of work but
Derek Jonese701d762010-03-02 18:17:01 -0600200 * it is extremely thorough, designed to prevent even the
Derek Jones37f4b9c2011-07-01 17:56:50 -0500201 * most obscure XSS attempts. Nothing is ever 100% foolproof,
Derek Jonese701d762010-03-02 18:17:01 -0600202 * of course, but I haven't been able to get anything passed
203 * the filter.
204 *
205 * Note: This function should only be used to deal with data
Derek Jones37f4b9c2011-07-01 17:56:50 -0500206 * upon submission. It's not something that should
Derek Jonese701d762010-03-02 18:17:01 -0600207 * be used for general runtime processing.
208 *
209 * This function was based in part on some code and ideas I
210 * got from Bitflux: http://channel.bitflux.ch/wiki/XSS_Prevention
211 *
212 * To help develop this script I used this great list of
213 * vulnerabilities along with a few other hacks I've
214 * harvested from examining vulnerabilities in other programs:
215 * http://ha.ckers.org/xss.html
216 *
Derek Jonese701d762010-03-02 18:17:01 -0600217 * @param mixed string or array
218 * @return string
219 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500220 public function xss_clean($str, $is_image = FALSE)
Derek Jonese701d762010-03-02 18:17:01 -0600221 {
222 /*
223 * Is the string an array?
224 *
225 */
226 if (is_array($str))
227 {
228 while (list($key) = each($str))
229 {
230 $str[$key] = $this->xss_clean($str[$key]);
231 }
Barry Mienydd671972010-10-04 16:33:58 +0200232
Derek Jonese701d762010-03-02 18:17:01 -0600233 return $str;
234 }
235
236 /*
237 * Remove Invisible Characters
238 */
Greg Aker757dda62010-04-14 19:06:19 -0500239 $str = remove_invisible_characters($str);
Derek Jonese701d762010-03-02 18:17:01 -0600240
Pascal Krietec9c045a2011-04-05 14:50:41 -0400241 // Validate Entities in URLs
242 $str = $this->_validate_entities($str);
Derek Jonese701d762010-03-02 18:17:01 -0600243
244 /*
245 * URL Decode
246 *
247 * Just in case stuff like this is submitted:
248 *
249 * <a href="http://%77%77%77%2E%67%6F%6F%67%6C%65%2E%63%6F%6D">Google</a>
250 *
251 * Note: Use rawurldecode() so it does not remove plus signs
252 *
253 */
254 $str = rawurldecode($str);
Barry Mienydd671972010-10-04 16:33:58 +0200255
Derek Jonese701d762010-03-02 18:17:01 -0600256 /*
Barry Mienydd671972010-10-04 16:33:58 +0200257 * Convert character entities to ASCII
Derek Jonese701d762010-03-02 18:17:01 -0600258 *
259 * This permits our tests below to work reliably.
260 * We only convert entities that are within tags since
261 * these are the ones that will pose security problems.
262 *
263 */
264
265 $str = preg_replace_callback("/[a-z]+=([\'\"]).*?\\1/si", array($this, '_convert_attribute'), $str);
Derek Jones37f4b9c2011-07-01 17:56:50 -0500266
Derek Jonese701d762010-03-02 18:17:01 -0600267 $str = preg_replace_callback("/<\w+.*?(?=>|<|$)/si", array($this, '_decode_entity'), $str);
268
269 /*
270 * Remove Invisible Characters Again!
271 */
Greg Aker757dda62010-04-14 19:06:19 -0500272 $str = remove_invisible_characters($str);
Barry Mienydd671972010-10-04 16:33:58 +0200273
Derek Jonese701d762010-03-02 18:17:01 -0600274 /*
275 * Convert all tabs to spaces
276 *
277 * This prevents strings like this: ja vascript
278 * NOTE: we deal with spaces between characters later.
Derek Jones37f4b9c2011-07-01 17:56:50 -0500279 * NOTE: preg_replace was found to be amazingly slow here on
Pascal Krietec9c045a2011-04-05 14:50:41 -0400280 * large blocks of data, so we use str_replace.
Derek Jonese701d762010-03-02 18:17:01 -0600281 */
Barry Mienydd671972010-10-04 16:33:58 +0200282
Derek Jonese701d762010-03-02 18:17:01 -0600283 if (strpos($str, "\t") !== FALSE)
284 {
285 $str = str_replace("\t", ' ', $str);
286 }
Barry Mienydd671972010-10-04 16:33:58 +0200287
Derek Jonese701d762010-03-02 18:17:01 -0600288 /*
289 * Capture converted string for later comparison
290 */
291 $converted_string = $str;
Barry Mienydd671972010-10-04 16:33:58 +0200292
Pascal Krietec9c045a2011-04-05 14:50:41 -0400293 // Remove Strings that are never allowed
294 $str = $this->_do_never_allowed($str);
Derek Jonese701d762010-03-02 18:17:01 -0600295
296 /*
297 * Makes PHP tags safe
298 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400299 * Note: XML tags are inadvertently replaced too:
Derek Jonese701d762010-03-02 18:17:01 -0600300 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400301 * <?xml
Derek Jonese701d762010-03-02 18:17:01 -0600302 *
303 * But it doesn't seem to pose a problem.
Derek Jonese701d762010-03-02 18:17:01 -0600304 */
305 if ($is_image === TRUE)
306 {
Derek Jones37f4b9c2011-07-01 17:56:50 -0500307 // Images have a tendency to have the PHP short opening and
308 // closing tags every so often so we skip those and only
Pascal Krietec9c045a2011-04-05 14:50:41 -0400309 // do the long opening tags.
Derek Jonese701d762010-03-02 18:17:01 -0600310 $str = preg_replace('/<\?(php)/i', "&lt;?\\1", $str);
311 }
312 else
313 {
Derek Jones37f4b9c2011-07-01 17:56:50 -0500314 $str = str_replace(array('<?', '?'.'>'), array('&lt;?', '?&gt;'), $str);
Derek Jonese701d762010-03-02 18:17:01 -0600315 }
Barry Mienydd671972010-10-04 16:33:58 +0200316
Derek Jonese701d762010-03-02 18:17:01 -0600317 /*
318 * Compact any exploded words
319 *
Derek Jones37f4b9c2011-07-01 17:56:50 -0500320 * This corrects words like: j a v a s c r i p t
Derek Jonese701d762010-03-02 18:17:01 -0600321 * These words are compacted back to their correct state.
Derek Jonese701d762010-03-02 18:17:01 -0600322 */
Pascal Krietec9c045a2011-04-05 14:50:41 -0400323 $words = array(
Derek Jones37f4b9c2011-07-01 17:56:50 -0500324 'javascript', 'expression', 'vbscript', 'script',
Pascal Krietec9c045a2011-04-05 14:50:41 -0400325 'applet', 'alert', 'document', 'write', 'cookie', 'window'
326 );
Derek Jones37f4b9c2011-07-01 17:56:50 -0500327
Derek Jonese701d762010-03-02 18:17:01 -0600328 foreach ($words as $word)
329 {
330 $temp = '';
Barry Mienydd671972010-10-04 16:33:58 +0200331
Derek Jonese701d762010-03-02 18:17:01 -0600332 for ($i = 0, $wordlen = strlen($word); $i < $wordlen; $i++)
333 {
334 $temp .= substr($word, $i, 1)."\s*";
335 }
336
337 // We only want to do this when it is followed by a non-word character
338 // That way valid stuff like "dealer to" does not become "dealerto"
339 $str = preg_replace_callback('#('.substr($temp, 0, -3).')(\W)#is', array($this, '_compact_exploded_words'), $str);
340 }
Barry Mienydd671972010-10-04 16:33:58 +0200341
Derek Jonese701d762010-03-02 18:17:01 -0600342 /*
343 * Remove disallowed Javascript in links or img tags
Derek Jones37f4b9c2011-07-01 17:56:50 -0500344 * We used to do some version comparisons and use of stripos for PHP5,
345 * but it is dog slow compared to these simplified non-capturing
Pascal Krietec9c045a2011-04-05 14:50:41 -0400346 * preg_match(), especially if the pattern exists in the string
Derek Jonese701d762010-03-02 18:17:01 -0600347 */
348 do
349 {
350 $original = $str;
Barry Mienydd671972010-10-04 16:33:58 +0200351
Derek Jonese701d762010-03-02 18:17:01 -0600352 if (preg_match("/<a/i", $str))
353 {
354 $str = preg_replace_callback("#<a\s+([^>]*?)(>|$)#si", array($this, '_js_link_removal'), $str);
355 }
Barry Mienydd671972010-10-04 16:33:58 +0200356
Derek Jonese701d762010-03-02 18:17:01 -0600357 if (preg_match("/<img/i", $str))
358 {
359 $str = preg_replace_callback("#<img\s+([^>]*?)(\s?/?>|$)#si", array($this, '_js_img_removal'), $str);
360 }
Barry Mienydd671972010-10-04 16:33:58 +0200361
Derek Jonese701d762010-03-02 18:17:01 -0600362 if (preg_match("/script/i", $str) OR preg_match("/xss/i", $str))
363 {
364 $str = preg_replace("#<(/*)(script|xss)(.*?)\>#si", '[removed]', $str);
365 }
366 }
Pascal Krietec9c045a2011-04-05 14:50:41 -0400367 while($original != $str);
Derek Jonese701d762010-03-02 18:17:01 -0600368
369 unset($original);
370
Pascal Krietec9c045a2011-04-05 14:50:41 -0400371 // Remove evil attributes such as style, onclick and xmlns
372 $str = $this->_remove_evil_attributes($str, $is_image);
Barry Mienydd671972010-10-04 16:33:58 +0200373
Derek Jonese701d762010-03-02 18:17:01 -0600374 /*
375 * Sanitize naughty HTML elements
376 *
377 * If a tag containing any of the words in the list
378 * below is found, the tag gets converted to entities.
379 *
380 * So this: <blink>
381 * Becomes: &lt;blink&gt;
Derek Jonese701d762010-03-02 18:17:01 -0600382 */
383 $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';
384 $str = preg_replace_callback('#<(/*\s*)('.$naughty.')([^><]*)([><]*)#is', array($this, '_sanitize_naughty_html'), $str);
385
386 /*
387 * Sanitize naughty scripting elements
388 *
389 * Similar to above, only instead of looking for
390 * tags it looks for PHP and JavaScript commands
Derek Jones37f4b9c2011-07-01 17:56:50 -0500391 * that are disallowed. Rather than removing the
Derek Jonese701d762010-03-02 18:17:01 -0600392 * code, it simply converts the parenthesis to entities
393 * rendering the code un-executable.
394 *
395 * For example: eval('some code')
396 * Becomes: eval&#40;'some code'&#41;
Derek Jonese701d762010-03-02 18:17:01 -0600397 */
398 $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 +0200399
Barry Mienydd671972010-10-04 16:33:58 +0200400
Pascal Krietec9c045a2011-04-05 14:50:41 -0400401 // Final clean up
402 // This adds a bit of extra precaution in case
403 // something got through the above filters
404 $str = $this->_do_never_allowed($str);
Derek Jonese701d762010-03-02 18:17:01 -0600405
406 /*
Pascal Krietec9c045a2011-04-05 14:50:41 -0400407 * Images are Handled in a Special Way
Derek Jones37f4b9c2011-07-01 17:56:50 -0500408 * - Essentially, we want to know that after all of the character
409 * conversion is done whether any unwanted, likely XSS, code was found.
Pascal Krietec9c045a2011-04-05 14:50:41 -0400410 * If not, we return TRUE, as the image is clean.
Derek Jones37f4b9c2011-07-01 17:56:50 -0500411 * However, if the string post-conversion does not matched the
412 * string post-removal of XSS, then it fails, as there was unwanted XSS
Pascal Krietec9c045a2011-04-05 14:50:41 -0400413 * code found and removed/changed during processing.
Derek Jonese701d762010-03-02 18:17:01 -0600414 */
415
416 if ($is_image === TRUE)
417 {
Pascal Krietec9c045a2011-04-05 14:50:41 -0400418 return ($str == $converted_string) ? TRUE: FALSE;
Derek Jonese701d762010-03-02 18:17:01 -0600419 }
Barry Mienydd671972010-10-04 16:33:58 +0200420
Derek Jonese701d762010-03-02 18:17:01 -0600421 log_message('debug', "XSS Filtering completed");
422 return $str;
423 }
424
425 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200426
Derek Jonese701d762010-03-02 18:17:01 -0600427 /**
428 * Random Hash for protecting URLs
429 *
Derek Jonese701d762010-03-02 18:17:01 -0600430 * @return string
431 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500432 public function xss_hash()
Barry Mienydd671972010-10-04 16:33:58 +0200433 {
Pascal Krietec9c045a2011-04-05 14:50:41 -0400434 if ($this->_xss_hash == '')
Derek Jonese701d762010-03-02 18:17:01 -0600435 {
436 if (phpversion() >= 4.2)
Derek Jonese701d762010-03-02 18:17:01 -0600437 {
Pascal Krietec9c045a2011-04-05 14:50:41 -0400438 mt_srand();
Derek Jonese701d762010-03-02 18:17:01 -0600439 }
Pascal Krietec9c045a2011-04-05 14:50:41 -0400440 else
441 {
442 mt_srand(hexdec(substr(md5(microtime()), -8)) & 0x7fffffff);
443 }
444
445 $this->_xss_hash = md5(time() + mt_rand(0, 1999999999));
Derek Jonese701d762010-03-02 18:17:01 -0600446 }
447
Pascal Krietec9c045a2011-04-05 14:50:41 -0400448 return $this->_xss_hash;
Derek Jonese701d762010-03-02 18:17:01 -0600449 }
450
451 // --------------------------------------------------------------------
452
453 /**
Derek Jonesa0911472010-03-30 10:33:09 -0500454 * HTML Entities Decode
455 *
456 * This function is a replacement for html_entity_decode()
457 *
458 * In some versions of PHP the native function does not work
459 * when UTF-8 is the specified character set, so this gives us
Derek Jones37f4b9c2011-07-01 17:56:50 -0500460 * a work-around. More info here:
Derek Jonesa0911472010-03-30 10:33:09 -0500461 * http://bugs.php.net/bug.php?id=25670
462 *
463 * NOTE: html_entity_decode() has a bug in some PHP versions when UTF-8 is the
464 * character set, and the PHP developers said they were not back porting the
465 * fix to versions other than PHP 5.x.
466 *
Derek Jonesa0911472010-03-30 10:33:09 -0500467 * @param string
468 * @param string
469 * @return string
470 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500471 public function entity_decode($str, $charset='UTF-8')
Derek Jonesa0911472010-03-30 10:33:09 -0500472 {
473 if (stristr($str, '&') === FALSE) return $str;
Barry Mienydd671972010-10-04 16:33:58 +0200474
Derek Jonesa0911472010-03-30 10:33:09 -0500475 // The reason we are not using html_entity_decode() by itself is because
476 // while it is not technically correct to leave out the semicolon
477 // at the end of an entity most browsers will still interpret the entity
Derek Jones37f4b9c2011-07-01 17:56:50 -0500478 // correctly. html_entity_decode() does not convert entities without
Derek Jonesa0911472010-03-30 10:33:09 -0500479 // semicolons, so we are left with our own little solution here. Bummer.
Barry Mienydd671972010-10-04 16:33:58 +0200480
Derek Jones37f4b9c2011-07-01 17:56:50 -0500481 if (function_exists('html_entity_decode') &&
Pascal Krietec9c045a2011-04-05 14:50:41 -0400482 (strtolower($charset) != 'utf-8'))
Derek Jonesa0911472010-03-30 10:33:09 -0500483 {
484 $str = html_entity_decode($str, ENT_COMPAT, $charset);
485 $str = preg_replace('~&#x(0*[0-9a-f]{2,5})~ei', 'chr(hexdec("\\1"))', $str);
486 return preg_replace('~&#([0-9]{2,4})~e', 'chr(\\1)', $str);
487 }
Barry Mienydd671972010-10-04 16:33:58 +0200488
Derek Jonesa0911472010-03-30 10:33:09 -0500489 // Numeric Entities
490 $str = preg_replace('~&#x(0*[0-9a-f]{2,5});{0,1}~ei', 'chr(hexdec("\\1"))', $str);
491 $str = preg_replace('~&#([0-9]{2,4});{0,1}~e', 'chr(\\1)', $str);
Barry Mienydd671972010-10-04 16:33:58 +0200492
Derek Jonesa0911472010-03-30 10:33:09 -0500493 // Literal Entities - Slightly slow so we do another check
494 if (stristr($str, '&') === FALSE)
495 {
496 $str = strtr($str, array_flip(get_html_translation_table(HTML_ENTITIES)));
497 }
Barry Mienydd671972010-10-04 16:33:58 +0200498
Derek Jonesa0911472010-03-30 10:33:09 -0500499 return $str;
500 }
Barry Mienydd671972010-10-04 16:33:58 +0200501
Derek Jonesa0911472010-03-30 10:33:09 -0500502 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200503
Derek Jonesa0911472010-03-30 10:33:09 -0500504 /**
Derek Jonese701d762010-03-02 18:17:01 -0600505 * Filename Security
506 *
Derek Jonese701d762010-03-02 18:17:01 -0600507 * @param string
508 * @return string
509 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500510 public function sanitize_filename($str, $relative_path = FALSE)
Derek Jonese701d762010-03-02 18:17:01 -0600511 {
512 $bad = array(
513 "../",
Derek Jonese701d762010-03-02 18:17:01 -0600514 "<!--",
515 "-->",
516 "<",
517 ">",
518 "'",
519 '"',
520 '&',
521 '$',
522 '#',
523 '{',
524 '}',
525 '[',
526 ']',
527 '=',
528 ';',
529 '?',
Derek Jonese701d762010-03-02 18:17:01 -0600530 "%20",
531 "%22",
532 "%3c", // <
Barry Mienydd671972010-10-04 16:33:58 +0200533 "%253c", // <
534 "%3e", // >
535 "%0e", // >
536 "%28", // (
537 "%29", // )
538 "%2528", // (
539 "%26", // &
540 "%24", // $
541 "%3f", // ?
542 "%3b", // ;
Derek Jonese701d762010-03-02 18:17:01 -0600543 "%3d" // =
544 );
Derek Jones37f4b9c2011-07-01 17:56:50 -0500545
Derek Jones2ef37592010-10-06 17:51:59 -0500546 if ( ! $relative_path)
547 {
548 $bad[] = './';
549 $bad[] = '/';
550 }
Derek Jonese701d762010-03-02 18:17:01 -0600551
Pascal Krietec9c045a2011-04-05 14:50:41 -0400552 $str = remove_invisible_characters($str, FALSE);
Derek Jonese701d762010-03-02 18:17:01 -0600553 return stripslashes(str_replace($bad, '', $str));
554 }
555
Pascal Krietec9c045a2011-04-05 14:50:41 -0400556 // ----------------------------------------------------------------
557
558 /**
559 * Compact Exploded Words
560 *
561 * Callback function for xss_clean() to remove whitespace from
562 * things like j a v a s c r i p t
563 *
564 * @param type
565 * @return type
566 */
567 protected function _compact_exploded_words($matches)
568 {
569 return preg_replace('/\s+/s', '', $matches[1]).$matches[2];
570 }
571
572 // --------------------------------------------------------------------
Derek Jones37f4b9c2011-07-01 17:56:50 -0500573
Pascal Krietec9c045a2011-04-05 14:50:41 -0400574 /*
575 * Remove Evil HTML Attributes (like evenhandlers and style)
576 *
577 * It removes the evil attribute and either:
578 * - Everything up until a space
579 * For example, everything between the pipes:
580 * <a |style=document.write('hello');alert('world');| class=link>
Derek Jones37f4b9c2011-07-01 17:56:50 -0500581 * - Everything inside the quotes
Pascal Krietec9c045a2011-04-05 14:50:41 -0400582 * For example, everything between the pipes:
583 * <a |style="document.write('hello'); alert('world');"| class="link">
584 *
585 * @param string $str The string to check
586 * @param boolean $is_image TRUE if this is an image
587 * @return string The string with the evil attributes removed
588 */
589 protected function _remove_evil_attributes($str, $is_image)
590 {
591 // All javascript event handlers (e.g. onload, onclick, onmouseover), style, and xmlns
592 $evil_attributes = array('on\w*', 'style', 'xmlns');
593
594 if ($is_image === TRUE)
595 {
596 /*
Derek Jones37f4b9c2011-07-01 17:56:50 -0500597 * Adobe Photoshop puts XML metadata into JFIF images,
Pascal Krietec9c045a2011-04-05 14:50:41 -0400598 * including namespacing, so we have to allow this for images.
599 */
600 unset($evil_attributes[array_search('xmlns', $evil_attributes)]);
601 }
Derek Jones37f4b9c2011-07-01 17:56:50 -0500602
Pascal Krietec9c045a2011-04-05 14:50:41 -0400603 do {
604 $str = preg_replace(
605 "#<(/?[^><]+?)([^A-Za-z\-])(".implode('|', $evil_attributes).")(\s*=\s*)([\"][^>]*?[\"]|[\'][^>]*?[\']|[^>]*?)([\s><])([><]*)#i",
606 "<$1$6",
607 $str, -1, $count
608 );
609 } while ($count);
Derek Jones37f4b9c2011-07-01 17:56:50 -0500610
Pascal Krietec9c045a2011-04-05 14:50:41 -0400611 return $str;
612 }
Derek Jones37f4b9c2011-07-01 17:56:50 -0500613
Pascal Krietec9c045a2011-04-05 14:50:41 -0400614 // --------------------------------------------------------------------
615
616 /**
617 * Sanitize Naughty HTML
618 *
619 * Callback function for xss_clean() to remove naughty HTML elements
620 *
621 * @param array
622 * @return string
623 */
624 protected function _sanitize_naughty_html($matches)
625 {
626 // encode opening brace
627 $str = '&lt;'.$matches[1].$matches[2].$matches[3];
628
629 // encode captured opening or closing brace to prevent recursive vectors
Derek Jones37f4b9c2011-07-01 17:56:50 -0500630 $str .= str_replace(array('>', '<'), array('&gt;', '&lt;'),
Pascal Krietec9c045a2011-04-05 14:50:41 -0400631 $matches[4]);
632
633 return $str;
634 }
635
636 // --------------------------------------------------------------------
637
638 /**
639 * JS Link Removal
640 *
641 * Callback function for xss_clean() to sanitize links
642 * This limits the PCRE backtracks, making it more performance friendly
643 * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in
644 * PHP 5.2+ on link-heavy strings
645 *
646 * @param array
647 * @return string
648 */
649 protected function _js_link_removal($match)
650 {
651 $attributes = $this->_filter_attributes(str_replace(array('<', '>'), '', $match[1]));
Derek Jones37f4b9c2011-07-01 17:56:50 -0500652
Pascal Krietec9c045a2011-04-05 14:50:41 -0400653 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]);
654 }
655
656 // --------------------------------------------------------------------
657
658 /**
659 * JS Image Removal
660 *
661 * Callback function for xss_clean() to sanitize image tags
662 * This limits the PCRE backtracks, making it more performance friendly
663 * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in
664 * PHP 5.2+ on image tag heavy strings
665 *
666 * @param array
667 * @return string
668 */
669 protected function _js_img_removal($match)
670 {
671 $attributes = $this->_filter_attributes(str_replace(array('<', '>'), '', $match[1]));
Derek Jones37f4b9c2011-07-01 17:56:50 -0500672
Pascal Krietec9c045a2011-04-05 14:50:41 -0400673 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]);
674 }
675
676 // --------------------------------------------------------------------
677
678 /**
679 * Attribute Conversion
680 *
681 * Used as a callback for XSS Clean
682 *
683 * @param array
684 * @return string
685 */
686 protected function _convert_attribute($match)
687 {
688 return str_replace(array('>', '<', '\\'), array('&gt;', '&lt;', '\\\\'), $match[0]);
689 }
690
691 // --------------------------------------------------------------------
692
693 /**
694 * Filter Attributes
695 *
696 * Filters tag attributes for consistency and safety
697 *
698 * @param string
699 * @return string
700 */
701 protected function _filter_attributes($str)
702 {
703 $out = '';
704
705 if (preg_match_all('#\s*[a-z\-]+\s*=\s*(\042|\047)([^\\1]*?)\\1#is', $str, $matches))
706 {
707 foreach ($matches[0] as $match)
708 {
709 $out .= preg_replace("#/\*.*?\*/#s", '', $match);
710 }
711 }
712
713 return $out;
714 }
715
716 // --------------------------------------------------------------------
717
718 /**
719 * HTML Entity Decode Callback
720 *
721 * Used as a callback for XSS Clean
722 *
723 * @param array
724 * @return string
725 */
726 protected function _decode_entity($match)
727 {
728 return $this->entity_decode($match[0], strtoupper(config_item('charset')));
729 }
730
731 // --------------------------------------------------------------------
Derek Jones37f4b9c2011-07-01 17:56:50 -0500732
Pascal Krietec9c045a2011-04-05 14:50:41 -0400733 /**
734 * Validate URL entities
735 *
736 * Called by xss_clean()
737 *
Derek Jones37f4b9c2011-07-01 17:56:50 -0500738 * @param string
Pascal Krietec9c045a2011-04-05 14:50:41 -0400739 * @return string
740 */
741 protected function _validate_entities($str)
742 {
743 /*
744 * Protect GET variables in URLs
745 */
Derek Jones37f4b9c2011-07-01 17:56:50 -0500746
Pascal Krietec9c045a2011-04-05 14:50:41 -0400747 // 901119URL5918AMP18930PROTECT8198
Derek Jones37f4b9c2011-07-01 17:56:50 -0500748
Pascal Krietec9c045a2011-04-05 14:50:41 -0400749 $str = preg_replace('|\&([a-z\_0-9\-]+)\=([a-z\_0-9\-]+)|i', $this->xss_hash()."\\1=\\2", $str);
750
751 /*
752 * Validate standard character entities
753 *
Derek Jones37f4b9c2011-07-01 17:56:50 -0500754 * Add a semicolon if missing. We do this to enable
Pascal Krietec9c045a2011-04-05 14:50:41 -0400755 * the conversion of entities to ASCII later.
756 *
757 */
758 $str = preg_replace('#(&\#?[0-9a-z]{2,})([\x00-\x20])*;?#i', "\\1;\\2", $str);
759
760 /*
761 * Validate UTF16 two byte encoding (x00)
762 *
763 * Just as above, adds a semicolon if missing.
764 *
765 */
766 $str = preg_replace('#(&\#x?)([0-9A-F]+);?#i',"\\1\\2;",$str);
767
768 /*
769 * Un-Protect GET variables in URLs
770 */
771 $str = str_replace($this->xss_hash(), '&', $str);
Derek Jones37f4b9c2011-07-01 17:56:50 -0500772
Pascal Krietec9c045a2011-04-05 14:50:41 -0400773 return $str;
774 }
775
776 // ----------------------------------------------------------------------
777
778 /**
779 * Do Never Allowed
780 *
781 * A utility function for xss_clean()
782 *
783 * @param string
784 * @return string
785 */
786 protected function _do_never_allowed($str)
787 {
788 foreach ($this->_never_allowed_str as $key => $val)
789 {
790 $str = str_replace($key, $val, $str);
791 }
792
793 foreach ($this->_never_allowed_regex as $key => $val)
794 {
795 $str = preg_replace("#".$key."#i", $val, $str);
796 }
Derek Jones37f4b9c2011-07-01 17:56:50 -0500797
Pascal Krietec9c045a2011-04-05 14:50:41 -0400798 return $str;
799 }
800
801 // --------------------------------------------------------------------
802
803 /**
804 * Set Cross Site Request Forgery Protection Cookie
805 *
806 * @return string
807 */
808 protected function _csrf_set_hash()
809 {
810 if ($this->_csrf_hash == '')
811 {
Derek Jones37f4b9c2011-07-01 17:56:50 -0500812 // If the cookie exists we will use it's value.
Pascal Krietec9c045a2011-04-05 14:50:41 -0400813 // We don't necessarily want to regenerate it with
Derek Jones37f4b9c2011-07-01 17:56:50 -0500814 // each page load since a page could contain embedded
Pascal Krietec9c045a2011-04-05 14:50:41 -0400815 // sub-pages causing this feature to fail
Derek Jones37f4b9c2011-07-01 17:56:50 -0500816 if (isset($_COOKIE[$this->_csrf_cookie_name]) &&
Pascal Krietec9c045a2011-04-05 14:50:41 -0400817 $_COOKIE[$this->_csrf_cookie_name] != '')
818 {
819 return $this->_csrf_hash = $_COOKIE[$this->_csrf_cookie_name];
820 }
Derek Jones37f4b9c2011-07-01 17:56:50 -0500821
Pascal Krietec9c045a2011-04-05 14:50:41 -0400822 return $this->_csrf_hash = md5(uniqid(rand(), TRUE));
823 }
824
825 return $this->_csrf_hash;
826 }
827
Derek Jonese701d762010-03-02 18:17:01 -0600828}
829// END Security Class
830
831/* End of file Security.php */
patworkef1a55a2011-04-09 13:04:06 +0200832/* Location: ./system/libraries/Security.php */