blob: 2bffa41b71b87171b87cb8fa0dbbc67407f85ce2 [file] [log] [blame]
Andrey Andreevbb488dc2012-01-07 23:35:16 +02001<?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 *
Derek Jonesf4a4bd82011-10-20 12:18:42 -05007 * NOTICE OF LICENSE
Andrey Andreevbb488dc2012-01-07 23:35:16 +02008 *
Derek Jonesf4a4bd82011-10-20 12:18:42 -05009 * Licensed under the Open Software License version 3.0
Andrey Andreevbb488dc2012-01-07 23:35:16 +020010 *
Derek Jonesf4a4bd82011-10-20 12:18:42 -050011 * This source file is subject to the Open Software License (OSL 3.0) that is
12 * bundled with this package in the files license.txt / license.rst. It is
13 * also available through the world wide web at this URL:
14 * http://opensource.org/licenses/OSL-3.0
15 * If you did not receive a copy of the license and are unable to obtain it
16 * through the world wide web, please send an email to
17 * licensing@ellislab.com so we can send you a copy immediately.
18 *
Derek Jonese701d762010-03-02 18:17:01 -060019 * @package CodeIgniter
Derek Jonesf4a4bd82011-10-20 12:18:42 -050020 * @author EllisLab Dev Team
Greg Aker0defe5d2012-01-01 18:46:41 -060021 * @copyright Copyright (c) 2008 - 2012, EllisLab, Inc. (http://ellislab.com/)
Derek Jonesf4a4bd82011-10-20 12:18:42 -050022 * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
Derek Jonese701d762010-03-02 18:17:01 -060023 * @link http://codeigniter.com
24 * @since Version 1.0
25 * @filesource
26 */
27
Derek Jonese701d762010-03-02 18:17:01 -060028/**
29 * Security Class
30 *
31 * @package CodeIgniter
32 * @subpackage Libraries
33 * @category Security
Derek Jonesf4a4bd82011-10-20 12:18:42 -050034 * @author EllisLab Dev Team
Pascal Krietec9c045a2011-04-05 14:50:41 -040035 * @link http://codeigniter.com/user_guide/libraries/security.html
Derek Jonese701d762010-03-02 18:17:01 -060036 */
37class CI_Security {
Barry Mienydd671972010-10-04 16:33:58 +020038
David Behler07b53422011-08-15 00:25:06 +020039 /**
40 * Random Hash for protecting URLs
41 *
42 * @var string
David Behler07b53422011-08-15 00:25:06 +020043 */
44 protected $_xss_hash = '';
Andrey Andreev3d113bd2011-10-05 00:03:20 +030045
David Behler07b53422011-08-15 00:25:06 +020046 /**
47 * Random Hash for Cross Site Request Forgery Protection Cookie
48 *
49 * @var string
David Behler07b53422011-08-15 00:25:06 +020050 */
51 protected $_csrf_hash = '';
Andrey Andreev3d113bd2011-10-05 00:03:20 +030052
David Behler07b53422011-08-15 00:25:06 +020053 /**
54 * Expiration time for Cross Site Request Forgery Protection Cookie
55 * Defaults to two hours (in seconds)
56 *
57 * @var int
David Behler07b53422011-08-15 00:25:06 +020058 */
59 protected $_csrf_expire = 7200;
Andrey Andreev3d113bd2011-10-05 00:03:20 +030060
David Behler07b53422011-08-15 00:25:06 +020061 /**
62 * Token name for Cross Site Request Forgery Protection Cookie
63 *
64 * @var string
David Behler07b53422011-08-15 00:25:06 +020065 */
66 protected $_csrf_token_name = 'ci_csrf_token';
Andrey Andreev3d113bd2011-10-05 00:03:20 +030067
David Behler07b53422011-08-15 00:25:06 +020068 /**
69 * Cookie name for Cross Site Request Forgery Protection Cookie
70 *
71 * @var string
David Behler07b53422011-08-15 00:25:06 +020072 */
Andrey Andreevbb488dc2012-01-07 23:35:16 +020073 protected $_csrf_cookie_name = 'ci_csrf_token';
Andrey Andreev3d113bd2011-10-05 00:03:20 +030074
David Behler07b53422011-08-15 00:25:06 +020075 /**
76 * List of never allowed strings
77 *
78 * @var array
David Behler07b53422011-08-15 00:25:06 +020079 */
Pascal Krietec9c045a2011-04-05 14:50:41 -040080 protected $_never_allowed_str = array(
Andrey Andreevbb488dc2012-01-07 23:35:16 +020081 'document.cookie' => '[removed]',
82 'document.write' => '[removed]',
83 '.parentNode' => '[removed]',
84 '.innerHTML' => '[removed]',
85 'window.location' => '[removed]',
86 '-moz-binding' => '[removed]',
87 '<!--' => '&lt;!--',
88 '-->' => '--&gt;',
89 '<![CDATA[' => '&lt;![CDATA[',
90 '<comment>' => '&lt;comment&gt;'
91 );
Derek Jonese701d762010-03-02 18:17:01 -060092
David Behler07b53422011-08-15 00:25:06 +020093 /**
94 * List of never allowed regex replacement
95 *
96 * @var array
David Behler07b53422011-08-15 00:25:06 +020097 */
Pascal Krietec9c045a2011-04-05 14:50:41 -040098 protected $_never_allowed_regex = array(
Andrey Andreevbb488dc2012-01-07 23:35:16 +020099 'javascript\s*:',
100 'expression\s*(\(|&\#40;)', // CSS and IE
101 'vbscript\s*:', // IE, surprise!
102 'Redirect\s+302'
103 );
David Behler07b53422011-08-15 00:25:06 +0200104
Greg Akera9263282010-11-10 15:26:43 -0600105 public function __construct()
Derek Jonese701d762010-03-02 18:17:01 -0600106 {
Andrey Andreev67ccdc02012-02-27 23:57:58 +0200107 // Is CSRF protection enabled?
108 if (config_item('csrf_protection') === TRUE)
patworkef1a55a2011-04-09 13:04:06 +0200109 {
Andrey Andreev67ccdc02012-02-27 23:57:58 +0200110 // CSRF config
111 foreach (array('csrf_expire', 'csrf_token_name', 'csrf_cookie_name') as $key)
patworkef1a55a2011-04-09 13:04:06 +0200112 {
Andrey Andreev67ccdc02012-02-27 23:57:58 +0200113 if (FALSE !== ($val = config_item($key)))
114 {
115 $this->{'_'.$key} = $val;
116 }
patworkef1a55a2011-04-09 13:04:06 +0200117 }
patworkef1a55a2011-04-09 13:04:06 +0200118
Andrey Andreev67ccdc02012-02-27 23:57:58 +0200119 // Append application specific cookie prefix
120 if (config_item('cookie_prefix'))
121 {
122 $this->_csrf_cookie_name = config_item('cookie_prefix').$this->_csrf_cookie_name;
123 }
Derek Jonesb3f10a22010-07-25 19:11:26 -0500124
Andrey Andreev67ccdc02012-02-27 23:57:58 +0200125 // Set the CSRF hash
126 $this->_csrf_set_hash();
127 }
Derek Allard958543a2010-07-22 14:10:26 -0400128
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200129 log_message('debug', 'Security Class Initialized');
Derek Jonese701d762010-03-02 18:17:01 -0600130 }
131
132 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200133
Derek Jonese701d762010-03-02 18:17:01 -0600134 /**
135 * Verify Cross Site Request Forgery Protection
136 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400137 * @return object
Derek Jonese701d762010-03-02 18:17:01 -0600138 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500139 public function csrf_verify()
Derek Allard958543a2010-07-22 14:10:26 -0400140 {
Andrey Andreev5d27c432012-03-08 12:01:52 +0200141 // If it's not a POST request we will set the CSRF cookie
142 if (strtoupper($_SERVER['REQUEST_METHOD']) !== 'POST')
Derek Jonese701d762010-03-02 18:17:01 -0600143 {
144 return $this->csrf_set_cookie();
145 }
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300146
Alex Bilbieaeb2c3e2011-08-21 16:14:54 +0100147 // Check if URI has been whitelisted from CSRF checks
148 if ($exclude_uris = config_item('csrf_exclude_uris'))
149 {
150 $uri = load_class('URI', 'core');
151 if (in_array($uri->uri_string(), $exclude_uris))
152 {
153 return $this;
154 }
155 }
Derek Jonese701d762010-03-02 18:17:01 -0600156
157 // Do the tokens exist in both the _POST and _COOKIE arrays?
Andrey Andreev4562f2c2012-01-09 23:39:50 +0200158 if ( ! isset($_POST[$this->_csrf_token_name]) OR ! isset($_COOKIE[$this->_csrf_cookie_name])
159 OR $_POST[$this->_csrf_token_name] != $_COOKIE[$this->_csrf_cookie_name]) // Do the tokens match?
Derek Jonese701d762010-03-02 18:17:01 -0600160 {
161 $this->csrf_show_error();
162 }
163
Andrey Andreev4562f2c2012-01-09 23:39:50 +0200164 // We kill this since we're done and we don't want to polute the _POST array
Pascal Krietec9c045a2011-04-05 14:50:41 -0400165 unset($_POST[$this->_csrf_token_name]);
Barry Mienydd671972010-10-04 16:33:58 +0200166
RS712be25a62011-12-31 16:02:04 -0200167 // Regenerate on every submission?
168 if (config_item('csrf_regenerate'))
169 {
170 // Nothing should last forever
171 unset($_COOKIE[$this->_csrf_cookie_name]);
172 $this->_csrf_hash = '';
173 }
Andrey Andreev8a7d0782012-01-08 05:43:42 +0200174
Derek Jonesb3f10a22010-07-25 19:11:26 -0500175 $this->_csrf_set_hash();
176 $this->csrf_set_cookie();
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300177
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200178 log_message('debug', 'CSRF token verified');
Pascal Krietec9c045a2011-04-05 14:50:41 -0400179 return $this;
Derek Jonese701d762010-03-02 18:17:01 -0600180 }
Barry Mienydd671972010-10-04 16:33:58 +0200181
Derek Jonese701d762010-03-02 18:17:01 -0600182 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200183
Derek Jonese701d762010-03-02 18:17:01 -0600184 /**
185 * Set Cross Site Request Forgery Protection Cookie
186 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400187 * @return object
Derek Jonese701d762010-03-02 18:17:01 -0600188 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500189 public function csrf_set_cookie()
Derek Jonese701d762010-03-02 18:17:01 -0600190 {
Pascal Krietec9c045a2011-04-05 14:50:41 -0400191 $expire = time() + $this->_csrf_expire;
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300192 $secure_cookie = (bool) config_item('cookie_secure');
Derek Jonese701d762010-03-02 18:17:01 -0600193
Andrey Andreeva10c8e12012-02-29 18:56:12 +0200194 if ($secure_cookie && (empty($_SERVER['HTTPS']) OR strtolower($_SERVER['HTTPS']) === 'off'))
Derek Jonese701d762010-03-02 18:17:01 -0600195 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200196 return FALSE;
Derek Jonese701d762010-03-02 18:17:01 -0600197 }
Derek Allard958543a2010-07-22 14:10:26 -0400198
Pascal Krietec9c045a2011-04-05 14:50:41 -0400199 setcookie($this->_csrf_cookie_name, $this->_csrf_hash, $expire, config_item('cookie_path'), config_item('cookie_domain'), $secure_cookie);
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200200 log_message('debug', 'CRSF cookie Set');
David Behler07b53422011-08-15 00:25:06 +0200201
Pascal Krietec9c045a2011-04-05 14:50:41 -0400202 return $this;
Derek Jonese701d762010-03-02 18:17:01 -0600203 }
204
205 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200206
Derek Jonese701d762010-03-02 18:17:01 -0600207 /**
208 * Show CSRF Error
209 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400210 * @return void
Derek Jonese701d762010-03-02 18:17:01 -0600211 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500212 public function csrf_show_error()
Derek Jonese701d762010-03-02 18:17:01 -0600213 {
214 show_error('The action you have requested is not allowed.');
215 }
216
217 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200218
Derek Jonese701d762010-03-02 18:17:01 -0600219 /**
David Behler07b53422011-08-15 00:25:06 +0200220 * Get CSRF Hash
Pascal Krietec9c045a2011-04-05 14:50:41 -0400221 *
David Behler07b53422011-08-15 00:25:06 +0200222 * Getter Method
Pascal Krietec9c045a2011-04-05 14:50:41 -0400223 *
224 * @return string self::_csrf_hash
225 */
226 public function get_csrf_hash()
227 {
228 return $this->_csrf_hash;
229 }
230
231 // --------------------------------------------------------------------
232
233 /**
234 * Get CSRF Token Name
235 *
236 * Getter Method
237 *
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200238 * @return string self::_csrf_token_name
Pascal Krietec9c045a2011-04-05 14:50:41 -0400239 */
240 public function get_csrf_token_name()
241 {
242 return $this->_csrf_token_name;
243 }
244
245 // --------------------------------------------------------------------
246
247 /**
Derek Jonese701d762010-03-02 18:17:01 -0600248 * XSS Clean
249 *
250 * Sanitizes data so that Cross Site Scripting Hacks can be
Derek Jones37f4b9c2011-07-01 17:56:50 -0500251 * prevented. This function does a fair amount of work but
Derek Jonese701d762010-03-02 18:17:01 -0600252 * it is extremely thorough, designed to prevent even the
Derek Jones37f4b9c2011-07-01 17:56:50 -0500253 * most obscure XSS attempts. Nothing is ever 100% foolproof,
Derek Jonese701d762010-03-02 18:17:01 -0600254 * of course, but I haven't been able to get anything passed
255 * the filter.
256 *
257 * Note: This function should only be used to deal with data
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200258 * upon submission. It's not something that should
Derek Jonese701d762010-03-02 18:17:01 -0600259 * be used for general runtime processing.
260 *
261 * This function was based in part on some code and ideas I
262 * got from Bitflux: http://channel.bitflux.ch/wiki/XSS_Prevention
263 *
264 * To help develop this script I used this great list of
265 * vulnerabilities along with a few other hacks I've
266 * harvested from examining vulnerabilities in other programs:
267 * http://ha.ckers.org/xss.html
268 *
Derek Jonese701d762010-03-02 18:17:01 -0600269 * @param mixed string or array
David Behler07b53422011-08-15 00:25:06 +0200270 * @param bool
Derek Jonese701d762010-03-02 18:17:01 -0600271 * @return string
272 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500273 public function xss_clean($str, $is_image = FALSE)
Derek Jonese701d762010-03-02 18:17:01 -0600274 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200275 // Is the string an array?
Derek Jonese701d762010-03-02 18:17:01 -0600276 if (is_array($str))
277 {
278 while (list($key) = each($str))
279 {
280 $str[$key] = $this->xss_clean($str[$key]);
281 }
Barry Mienydd671972010-10-04 16:33:58 +0200282
Derek Jonese701d762010-03-02 18:17:01 -0600283 return $str;
284 }
285
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200286 // Remove Invisible Characters and validate entities in URLs
287 $str = $this->_validate_entities(remove_invisible_characters($str));
Derek Jonese701d762010-03-02 18:17:01 -0600288
289 /*
290 * URL Decode
291 *
292 * Just in case stuff like this is submitted:
293 *
294 * <a href="http://%77%77%77%2E%67%6F%6F%67%6C%65%2E%63%6F%6D">Google</a>
295 *
296 * Note: Use rawurldecode() so it does not remove plus signs
Derek Jonese701d762010-03-02 18:17:01 -0600297 */
298 $str = rawurldecode($str);
Barry Mienydd671972010-10-04 16:33:58 +0200299
Derek Jonese701d762010-03-02 18:17:01 -0600300 /*
Barry Mienydd671972010-10-04 16:33:58 +0200301 * Convert character entities to ASCII
Derek Jonese701d762010-03-02 18:17:01 -0600302 *
303 * This permits our tests below to work reliably.
304 * We only convert entities that are within tags since
305 * these are the ones that will pose security problems.
Derek Jonese701d762010-03-02 18:17:01 -0600306 */
Derek Jonese701d762010-03-02 18:17:01 -0600307 $str = preg_replace_callback("/[a-z]+=([\'\"]).*?\\1/si", array($this, '_convert_attribute'), $str);
Andrey Andreev4562f2c2012-01-09 23:39:50 +0200308 $str = preg_replace_callback('/<\w+.*?(?=>|<|$)/si', array($this, '_decode_entity'), $str);
Derek Jonese701d762010-03-02 18:17:01 -0600309
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200310 // Remove Invisible Characters Again!
Greg Aker757dda62010-04-14 19:06:19 -0500311 $str = remove_invisible_characters($str);
Barry Mienydd671972010-10-04 16:33:58 +0200312
Derek Jonese701d762010-03-02 18:17:01 -0600313 /*
314 * Convert all tabs to spaces
315 *
316 * This prevents strings like this: ja vascript
317 * NOTE: we deal with spaces between characters later.
David Behler07b53422011-08-15 00:25:06 +0200318 * NOTE: preg_replace was found to be amazingly slow here on
Pascal Krietec9c045a2011-04-05 14:50:41 -0400319 * large blocks of data, so we use str_replace.
Derek Jonese701d762010-03-02 18:17:01 -0600320 */
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200321 $str = str_replace("\t", ' ', $str);
Barry Mienydd671972010-10-04 16:33:58 +0200322
Andrey Andreev4562f2c2012-01-09 23:39:50 +0200323 // Capture converted string for later comparison
Derek Jonese701d762010-03-02 18:17:01 -0600324 $converted_string = $str;
Barry Mienydd671972010-10-04 16:33:58 +0200325
Pascal Krietec9c045a2011-04-05 14:50:41 -0400326 // Remove Strings that are never allowed
327 $str = $this->_do_never_allowed($str);
Derek Jonese701d762010-03-02 18:17:01 -0600328
329 /*
330 * Makes PHP tags safe
331 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400332 * Note: XML tags are inadvertently replaced too:
Derek Jonese701d762010-03-02 18:17:01 -0600333 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400334 * <?xml
Derek Jonese701d762010-03-02 18:17:01 -0600335 *
336 * But it doesn't seem to pose a problem.
Derek Jonese701d762010-03-02 18:17:01 -0600337 */
338 if ($is_image === TRUE)
339 {
David Behler07b53422011-08-15 00:25:06 +0200340 // Images have a tendency to have the PHP short opening and
341 // closing tags every so often so we skip those and only
Pascal Krietec9c045a2011-04-05 14:50:41 -0400342 // do the long opening tags.
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200343 $str = preg_replace('/<\?(php)/i', '&lt;?\\1', $str);
Derek Jonese701d762010-03-02 18:17:01 -0600344 }
345 else
346 {
Derek Jones37f4b9c2011-07-01 17:56:50 -0500347 $str = str_replace(array('<?', '?'.'>'), array('&lt;?', '?&gt;'), $str);
Derek Jonese701d762010-03-02 18:17:01 -0600348 }
Barry Mienydd671972010-10-04 16:33:58 +0200349
Derek Jonese701d762010-03-02 18:17:01 -0600350 /*
351 * Compact any exploded words
352 *
Derek Jones37f4b9c2011-07-01 17:56:50 -0500353 * This corrects words like: j a v a s c r i p t
Derek Jonese701d762010-03-02 18:17:01 -0600354 * These words are compacted back to their correct state.
Derek Jonese701d762010-03-02 18:17:01 -0600355 */
Pascal Krietec9c045a2011-04-05 14:50:41 -0400356 $words = array(
David Behler07b53422011-08-15 00:25:06 +0200357 'javascript', 'expression', 'vbscript', 'script',
Pascal Krietec9c045a2011-04-05 14:50:41 -0400358 'applet', 'alert', 'document', 'write', 'cookie', 'window'
359 );
David Behler07b53422011-08-15 00:25:06 +0200360
Derek Jonese701d762010-03-02 18:17:01 -0600361 foreach ($words as $word)
362 {
Andrey Andreev67ccdc02012-02-27 23:57:58 +0200363 $word = implode('\s*', str_split($word)).'\s*';
Derek Jonese701d762010-03-02 18:17:01 -0600364
365 // We only want to do this when it is followed by a non-word character
366 // That way valid stuff like "dealer to" does not become "dealerto"
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300367 $str = preg_replace_callback('#('.substr($word, 0, -3).')(\W)#is', array($this, '_compact_exploded_words'), $str);
Derek Jonese701d762010-03-02 18:17:01 -0600368 }
Barry Mienydd671972010-10-04 16:33:58 +0200369
Derek Jonese701d762010-03-02 18:17:01 -0600370 /*
371 * Remove disallowed Javascript in links or img tags
David Behler07b53422011-08-15 00:25:06 +0200372 * We used to do some version comparisons and use of stripos for PHP5,
373 * but it is dog slow compared to these simplified non-capturing
Pascal Krietec9c045a2011-04-05 14:50:41 -0400374 * preg_match(), especially if the pattern exists in the string
Derek Jonese701d762010-03-02 18:17:01 -0600375 */
376 do
377 {
378 $original = $str;
Barry Mienydd671972010-10-04 16:33:58 +0200379
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200380 if (preg_match('/<a/i', $str))
Derek Jonese701d762010-03-02 18:17:01 -0600381 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200382 $str = preg_replace_callback('#<a\s+([^>]*?)(>|$)#si', array($this, '_js_link_removal'), $str);
Derek Jonese701d762010-03-02 18:17:01 -0600383 }
Barry Mienydd671972010-10-04 16:33:58 +0200384
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200385 if (preg_match('/<img/i', $str))
Derek Jonese701d762010-03-02 18:17:01 -0600386 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200387 $str = preg_replace_callback('#<img\s+([^>]*?)(\s?/?>|$)#si', array($this, '_js_img_removal'), $str);
Derek Jonese701d762010-03-02 18:17:01 -0600388 }
Barry Mienydd671972010-10-04 16:33:58 +0200389
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200390 if (preg_match('/(script|xss)/i', $str))
Derek Jonese701d762010-03-02 18:17:01 -0600391 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200392 $str = preg_replace('#<(/*)(script|xss)(.*?)\>#si', '[removed]', $str);
Derek Jonese701d762010-03-02 18:17:01 -0600393 }
394 }
Pascal Krietec9c045a2011-04-05 14:50:41 -0400395 while($original != $str);
Derek Jonese701d762010-03-02 18:17:01 -0600396
397 unset($original);
398
Pascal Krietec9c045a2011-04-05 14:50:41 -0400399 // Remove evil attributes such as style, onclick and xmlns
400 $str = $this->_remove_evil_attributes($str, $is_image);
Barry Mienydd671972010-10-04 16:33:58 +0200401
Derek Jonese701d762010-03-02 18:17:01 -0600402 /*
403 * Sanitize naughty HTML elements
404 *
405 * If a tag containing any of the words in the list
406 * below is found, the tag gets converted to entities.
407 *
408 * So this: <blink>
409 * Becomes: &lt;blink&gt;
Derek Jonese701d762010-03-02 18:17:01 -0600410 */
411 $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';
412 $str = preg_replace_callback('#<(/*\s*)('.$naughty.')([^><]*)([><]*)#is', array($this, '_sanitize_naughty_html'), $str);
413
414 /*
415 * Sanitize naughty scripting elements
416 *
417 * Similar to above, only instead of looking for
418 * tags it looks for PHP and JavaScript commands
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200419 * that are disallowed. Rather than removing the
Derek Jonese701d762010-03-02 18:17:01 -0600420 * code, it simply converts the parenthesis to entities
421 * rendering the code un-executable.
422 *
423 * For example: eval('some code')
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200424 * Becomes: eval&#40;'some code'&#41;
Derek Jonese701d762010-03-02 18:17:01 -0600425 */
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200426 $str = preg_replace('#(alert|cmd|passthru|eval|exec|expression|system|fopen|fsockopen|file|file_get_contents|readfile|unlink)(\s*)\((.*?)\)#si',
427 '\\1\\2&#40;\\3&#41;',
428 $str);
Barry Mienydd671972010-10-04 16:33:58 +0200429
Pascal Krietec9c045a2011-04-05 14:50:41 -0400430 // Final clean up
431 // This adds a bit of extra precaution in case
432 // something got through the above filters
433 $str = $this->_do_never_allowed($str);
Derek Jonese701d762010-03-02 18:17:01 -0600434
435 /*
Pascal Krietec9c045a2011-04-05 14:50:41 -0400436 * Images are Handled in a Special Way
David Behler07b53422011-08-15 00:25:06 +0200437 * - Essentially, we want to know that after all of the character
438 * conversion is done whether any unwanted, likely XSS, code was found.
Pascal Krietec9c045a2011-04-05 14:50:41 -0400439 * If not, we return TRUE, as the image is clean.
David Behler07b53422011-08-15 00:25:06 +0200440 * However, if the string post-conversion does not matched the
441 * string post-removal of XSS, then it fails, as there was unwanted XSS
Pascal Krietec9c045a2011-04-05 14:50:41 -0400442 * code found and removed/changed during processing.
Derek Jonese701d762010-03-02 18:17:01 -0600443 */
Derek Jonese701d762010-03-02 18:17:01 -0600444 if ($is_image === TRUE)
445 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200446 return ($str === $converted_string);
Derek Jonese701d762010-03-02 18:17:01 -0600447 }
Barry Mienydd671972010-10-04 16:33:58 +0200448
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200449 log_message('debug', 'XSS Filtering completed');
Derek Jonese701d762010-03-02 18:17:01 -0600450 return $str;
451 }
452
453 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200454
Derek Jonese701d762010-03-02 18:17:01 -0600455 /**
456 * Random Hash for protecting URLs
457 *
Derek Jonese701d762010-03-02 18:17:01 -0600458 * @return string
459 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500460 public function xss_hash()
Barry Mienydd671972010-10-04 16:33:58 +0200461 {
Pascal Krietec9c045a2011-04-05 14:50:41 -0400462 if ($this->_xss_hash == '')
Derek Jonese701d762010-03-02 18:17:01 -0600463 {
Pascal Krietec38e3b62011-11-14 13:55:00 -0500464 mt_srand();
Pascal Krietec9c045a2011-04-05 14:50:41 -0400465 $this->_xss_hash = md5(time() + mt_rand(0, 1999999999));
Derek Jonese701d762010-03-02 18:17:01 -0600466 }
467
Pascal Krietec9c045a2011-04-05 14:50:41 -0400468 return $this->_xss_hash;
Derek Jonese701d762010-03-02 18:17:01 -0600469 }
470
471 // --------------------------------------------------------------------
472
473 /**
Derek Jonesa0911472010-03-30 10:33:09 -0500474 * HTML Entities Decode
475 *
476 * This function is a replacement for html_entity_decode()
477 *
Pascal Krietec38e3b62011-11-14 13:55:00 -0500478 * The reason we are not using html_entity_decode() by itself is because
479 * while it is not technically correct to leave out the semicolon
480 * at the end of an entity most browsers will still interpret the entity
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200481 * correctly. html_entity_decode() does not convert entities without
Pascal Krietec38e3b62011-11-14 13:55:00 -0500482 * semicolons, so we are left with our own little solution here. Bummer.
Derek Jonesa0911472010-03-30 10:33:09 -0500483 *
Derek Jonesa0911472010-03-30 10:33:09 -0500484 * @param string
485 * @param string
486 * @return string
487 */
freewil8cc0cfe2011-08-27 21:53:00 -0400488 public function entity_decode($str, $charset = NULL)
Derek Jonesa0911472010-03-30 10:33:09 -0500489 {
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300490 if (strpos($str, '&') === FALSE)
freewil5c9b0d12011-08-28 12:15:23 -0400491 {
492 return $str;
493 }
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300494
freewil5c9b0d12011-08-28 12:15:23 -0400495 if (empty($charset))
496 {
497 $charset = config_item('charset');
498 }
Barry Mienydd671972010-10-04 16:33:58 +0200499
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300500 $str = html_entity_decode($str, ENT_COMPAT, $charset);
501 $str = preg_replace('~&#x(0*[0-9a-f]{2,5})~ei', 'chr(hexdec("\\1"))', $str);
502 return preg_replace('~&#([0-9]{2,4})~e', 'chr(\\1)', $str);
Derek Jonesa0911472010-03-30 10:33:09 -0500503 }
Barry Mienydd671972010-10-04 16:33:58 +0200504
Derek Jonesa0911472010-03-30 10:33:09 -0500505 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200506
Derek Jonesa0911472010-03-30 10:33:09 -0500507 /**
Derek Jonese701d762010-03-02 18:17:01 -0600508 * Filename Security
509 *
Derek Jonese701d762010-03-02 18:17:01 -0600510 * @param string
David Behler07b53422011-08-15 00:25:06 +0200511 * @param bool
Derek Jonese701d762010-03-02 18:17:01 -0600512 * @return string
513 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500514 public function sanitize_filename($str, $relative_path = FALSE)
Derek Jonese701d762010-03-02 18:17:01 -0600515 {
516 $bad = array(
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200517 '../', '<!--', '-->', '<', '>',
518 "'", '"', '&', '$', '#',
519 '{', '}', '[', ']', '=',
520 ';', '?', '%20', '%22',
521 '%3c', // <
522 '%253c', // <
523 '%3e', // >
524 '%0e', // >
525 '%28', // (
526 '%29', // )
527 '%2528', // (
528 '%26', // &
529 '%24', // $
530 '%3f', // ?
531 '%3b', // ;
532 '%3d' // =
533 );
David Behler07b53422011-08-15 00:25:06 +0200534
Derek Jones2ef37592010-10-06 17:51:59 -0500535 if ( ! $relative_path)
536 {
537 $bad[] = './';
538 $bad[] = '/';
539 }
Derek Jonese701d762010-03-02 18:17:01 -0600540
Pascal Krietec9c045a2011-04-05 14:50:41 -0400541 $str = remove_invisible_characters($str, FALSE);
Derek Jonese701d762010-03-02 18:17:01 -0600542 return stripslashes(str_replace($bad, '', $str));
543 }
544
Pascal Krietec9c045a2011-04-05 14:50:41 -0400545 // ----------------------------------------------------------------
546
547 /**
548 * Compact Exploded Words
549 *
550 * Callback function for xss_clean() to remove whitespace from
551 * things like j a v a s c r i p t
552 *
553 * @param type
554 * @return type
555 */
556 protected function _compact_exploded_words($matches)
557 {
558 return preg_replace('/\s+/s', '', $matches[1]).$matches[2];
559 }
560
561 // --------------------------------------------------------------------
David Behler07b53422011-08-15 00:25:06 +0200562
Pascal Krietec9c045a2011-04-05 14:50:41 -0400563 /*
564 * Remove Evil HTML Attributes (like evenhandlers and style)
565 *
566 * It removes the evil attribute and either:
567 * - Everything up until a space
568 * For example, everything between the pipes:
569 * <a |style=document.write('hello');alert('world');| class=link>
David Behler07b53422011-08-15 00:25:06 +0200570 * - Everything inside the quotes
Pascal Krietec9c045a2011-04-05 14:50:41 -0400571 * For example, everything between the pipes:
572 * <a |style="document.write('hello'); alert('world');"| class="link">
573 *
574 * @param string $str The string to check
575 * @param boolean $is_image TRUE if this is an image
576 * @return string The string with the evil attributes removed
577 */
578 protected function _remove_evil_attributes($str, $is_image)
579 {
580 // All javascript event handlers (e.g. onload, onclick, onmouseover), style, and xmlns
Pascal Krietec38e3b62011-11-14 13:55:00 -0500581 $evil_attributes = array('on\w*', 'style', 'xmlns', 'formaction');
Pascal Krietec9c045a2011-04-05 14:50:41 -0400582
583 if ($is_image === TRUE)
584 {
585 /*
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200586 * Adobe Photoshop puts XML metadata into JFIF images,
Pascal Krietec9c045a2011-04-05 14:50:41 -0400587 * including namespacing, so we have to allow this for images.
588 */
589 unset($evil_attributes[array_search('xmlns', $evil_attributes)]);
590 }
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200591
Pascal Krietec9c045a2011-04-05 14:50:41 -0400592 do {
Pascal Krietec38e3b62011-11-14 13:55:00 -0500593 $count = 0;
594 $attribs = array();
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200595
Pascal Krietec38e3b62011-11-14 13:55:00 -0500596 // find occurrences of illegal attribute strings without quotes
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200597 preg_match_all('/('.implode('|', $evil_attributes).')\s*=\s*([^\s]*)/is', $str, $matches, PREG_SET_ORDER);
598
Pascal Krietec38e3b62011-11-14 13:55:00 -0500599 foreach ($matches as $attr)
600 {
601 $attribs[] = preg_quote($attr[0], '/');
602 }
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200603
Pascal Krietec38e3b62011-11-14 13:55:00 -0500604 // find occurrences of illegal attribute strings with quotes (042 and 047 are octal quotes)
Andrey Andreev67ccdc02012-02-27 23:57:58 +0200605 preg_match_all('/('.implode('|', $evil_attributes).')\s*=\s*(\042|\047)([^\\2]*?)(\\2)/is', $str, $matches, PREG_SET_ORDER);
David Behler07b53422011-08-15 00:25:06 +0200606
Pascal Krietec38e3b62011-11-14 13:55:00 -0500607 foreach ($matches as $attr)
608 {
609 $attribs[] = preg_quote($attr[0], '/');
610 }
611
612 // replace illegal attribute strings that are inside an html tag
613 if (count($attribs) > 0)
614 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200615 $str = preg_replace('/<(\/?[^><]+?)([^A-Za-z\-])('.implode('|', $attribs).')([\s><])([><]*)/i', '<$1$2$4$5', $str, -1, $count);
Pascal Krietec38e3b62011-11-14 13:55:00 -0500616 }
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200617
Pascal Krietec38e3b62011-11-14 13:55:00 -0500618 } while ($count);
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200619
Pascal Krietec9c045a2011-04-05 14:50:41 -0400620 return $str;
621 }
David Behler07b53422011-08-15 00:25:06 +0200622
Pascal Krietec9c045a2011-04-05 14:50:41 -0400623 // --------------------------------------------------------------------
624
625 /**
626 * Sanitize Naughty HTML
627 *
628 * Callback function for xss_clean() to remove naughty HTML elements
629 *
630 * @param array
631 * @return string
632 */
633 protected function _sanitize_naughty_html($matches)
634 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200635 return '&lt;'.$matches[1].$matches[2].$matches[3] // encode opening brace
636 // encode captured opening or closing brace to prevent recursive vectors:
Andrey Andreev67ccdc02012-02-27 23:57:58 +0200637 .str_replace(array('>', '<'), array('&gt;', '&lt;'), $matches[4]);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400638 }
639
640 // --------------------------------------------------------------------
641
642 /**
643 * JS Link Removal
644 *
645 * Callback function for xss_clean() to sanitize links
646 * This limits the PCRE backtracks, making it more performance friendly
647 * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in
648 * PHP 5.2+ on link-heavy strings
649 *
650 * @param array
651 * @return string
652 */
653 protected function _js_link_removal($match)
654 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200655 return str_replace($match[1],
656 preg_replace('#href=.*?(alert\(|alert&\#40;|javascript\:|livescript\:|mocha\:|charset\=|window\.|document\.|\.cookie|<script|<xss|base64\s*,)#si',
657 '',
658 $this->_filter_attributes(str_replace(array('<', '>'), '', $match[1]))
659 ),
660 $match[0]);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400661 }
662
663 // --------------------------------------------------------------------
664
665 /**
666 * JS Image Removal
667 *
668 * Callback function for xss_clean() to sanitize image tags
669 * This limits the PCRE backtracks, making it more performance friendly
670 * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in
671 * PHP 5.2+ on image tag heavy strings
672 *
673 * @param array
674 * @return string
675 */
676 protected function _js_img_removal($match)
677 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200678 return str_replace($match[1],
679 preg_replace('#src=.*?(alert\(|alert&\#40;|javascript\:|livescript\:|mocha\:|charset\=|window\.|document\.|\.cookie|<script|<xss|base64\s*,)#si',
680 '',
681 $this->_filter_attributes(str_replace(array('<', '>'), '', $match[1]))
682 ),
683 $match[0]);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400684 }
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 = '';
Pascal Krietec9c045a2011-04-05 14:50:41 -0400714 if (preg_match_all('#\s*[a-z\-]+\s*=\s*(\042|\047)([^\\1]*?)\\1#is', $str, $matches))
715 {
716 foreach ($matches[0] as $match)
717 {
Andrey Andreev4562f2c2012-01-09 23:39:50 +0200718 $out .= preg_replace('#/\*.*?\*/#s', '', $match);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400719 }
720 }
721
722 return $out;
723 }
724
725 // --------------------------------------------------------------------
726
727 /**
728 * HTML Entity Decode Callback
729 *
730 * Used as a callback for XSS Clean
731 *
732 * @param array
733 * @return string
734 */
735 protected function _decode_entity($match)
736 {
737 return $this->entity_decode($match[0], strtoupper(config_item('charset')));
738 }
739
740 // --------------------------------------------------------------------
David Behler07b53422011-08-15 00:25:06 +0200741
Pascal Krietec9c045a2011-04-05 14:50:41 -0400742 /**
743 * Validate URL entities
744 *
745 * Called by xss_clean()
746 *
David Behler07b53422011-08-15 00:25:06 +0200747 * @param string
Pascal Krietec9c045a2011-04-05 14:50:41 -0400748 * @return string
749 */
750 protected function _validate_entities($str)
751 {
752 /*
753 * Protect GET variables in URLs
754 */
David Behler07b53422011-08-15 00:25:06 +0200755
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200756 // 901119URL5918AMP18930PROTECT8198
757 $str = preg_replace('|\&([a-z\_0-9\-]+)\=([a-z\_0-9\-]+)|i', $this->xss_hash().'\\1=\\2', $str);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400758
759 /*
760 * Validate standard character entities
761 *
Derek Jones37f4b9c2011-07-01 17:56:50 -0500762 * Add a semicolon if missing. We do this to enable
Pascal Krietec9c045a2011-04-05 14:50:41 -0400763 * the conversion of entities to ASCII later.
Pascal Krietec9c045a2011-04-05 14:50:41 -0400764 */
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200765 $str = preg_replace('#(&\#?[0-9a-z]{2,})([\x00-\x20])*;?#i', '\\1;\\2', $str);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400766
767 /*
768 * Validate UTF16 two byte encoding (x00)
769 *
770 * Just as above, adds a semicolon if missing.
Pascal Krietec9c045a2011-04-05 14:50:41 -0400771 */
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200772 $str = preg_replace('#(&\#x?)([0-9A-F]+);?#i', '\\1\\2;', $str);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400773
774 /*
775 * Un-Protect GET variables in URLs
776 */
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200777 return str_replace($this->xss_hash(), '&', $str);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400778 }
779
780 // ----------------------------------------------------------------------
781
782 /**
783 * Do Never Allowed
784 *
785 * A utility function for xss_clean()
786 *
787 * @param string
788 * @return string
789 */
790 protected function _do_never_allowed($str)
791 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200792 $str = str_replace(array_keys($this->_never_allowed_str), $this->_never_allowed_str, $str);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400793
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200794 foreach ($this->_never_allowed_regex as $regex)
Pascal Krietec9c045a2011-04-05 14:50:41 -0400795 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200796 $str = preg_replace('#'.$regex.'#i', '[removed]', $str);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400797 }
David Behler07b53422011-08-15 00:25:06 +0200798
Pascal Krietec9c045a2011-04-05 14:50:41 -0400799 return $str;
800 }
801
802 // --------------------------------------------------------------------
803
804 /**
805 * Set Cross Site Request Forgery Protection Cookie
806 *
807 * @return string
808 */
809 protected function _csrf_set_hash()
810 {
811 if ($this->_csrf_hash == '')
812 {
David Behler07b53422011-08-15 00:25:06 +0200813 // If the cookie exists we will use it's value.
Pascal Krietec9c045a2011-04-05 14:50:41 -0400814 // We don't necessarily want to regenerate it with
David Behler07b53422011-08-15 00:25:06 +0200815 // each page load since a page could contain embedded
Pascal Krietec9c045a2011-04-05 14:50:41 -0400816 // sub-pages causing this feature to fail
David Behler07b53422011-08-15 00:25:06 +0200817 if (isset($_COOKIE[$this->_csrf_cookie_name]) &&
Pascal Krietec9c045a2011-04-05 14:50:41 -0400818 $_COOKIE[$this->_csrf_cookie_name] != '')
819 {
820 return $this->_csrf_hash = $_COOKIE[$this->_csrf_cookie_name];
821 }
David Behler07b53422011-08-15 00:25:06 +0200822
Chris Berthed93e6f32011-09-25 10:33:25 -0400823 $this->_csrf_hash = md5(uniqid(rand(), TRUE));
824 $this->csrf_set_cookie();
Pascal Krietec9c045a2011-04-05 14:50:41 -0400825 }
826
827 return $this->_csrf_hash;
828 }
829
Derek Jonese701d762010-03-02 18:17:01 -0600830}
Derek Jonese701d762010-03-02 18:17:01 -0600831
832/* End of file Security.php */
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200833/* Location: ./system/core/Security.php */