blob: c82b69ff9b1b9462402e9f120d718f9bea53a3b4 [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 *
Phil Sturgeon07c1ac82012-03-09 17:03:37 +00005 * An open source application development framework for PHP 5.2.4 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 */
Timothy Warren48a7fbb2012-04-23 11:58:16 -040044 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 */
Timothy Warren48a7fbb2012-04-23 11:58:16 -040051 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 */
Timothy Warren48a7fbb2012-04-23 11:58:16 -040059 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 */
Timothy Warren48a7fbb2012-04-23 11:58:16 -040066 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 */
Timothy Warren48a7fbb2012-04-23 11:58:16 -040073 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 */
Timothy Warren48a7fbb2012-04-23 11:58:16 -040080 protected $_never_allowed_str = array(
Timothy Warren40403d22012-04-19 16:38:50 -040081 '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(
Timothy Warren40403d22012-04-19 16:38:50 -040099 'javascript\s*:',
100 'expression\s*(\(|&\#40;)', // CSS and IE
101 'vbscript\s*:', // IE, surprise!
Wes Bakerd3481352012-05-07 16:49:33 -0400102 'Redirect\s+302',
103 "([\"'])?data\s*:[^\\1]*?base64[^\\1]*?,[^\\1]*?\\1?"
Timothy Warren40403d22012-04-19 16:38:50 -0400104 );
Wes Bakerd3481352012-05-07 16:49:33 -0400105
Timothy Warrenad475052012-04-19 13:21:06 -0400106 /**
107 * Initialize security class
108 */
Greg Akera9263282010-11-10 15:26:43 -0600109 public function __construct()
Derek Jonese701d762010-03-02 18:17:01 -0600110 {
Andrey Andreev67ccdc02012-02-27 23:57:58 +0200111 // Is CSRF protection enabled?
112 if (config_item('csrf_protection') === TRUE)
patworkef1a55a2011-04-09 13:04:06 +0200113 {
Andrey Andreev67ccdc02012-02-27 23:57:58 +0200114 // CSRF config
115 foreach (array('csrf_expire', 'csrf_token_name', 'csrf_cookie_name') as $key)
patworkef1a55a2011-04-09 13:04:06 +0200116 {
Andrey Andreev67ccdc02012-02-27 23:57:58 +0200117 if (FALSE !== ($val = config_item($key)))
118 {
119 $this->{'_'.$key} = $val;
120 }
patworkef1a55a2011-04-09 13:04:06 +0200121 }
patworkef1a55a2011-04-09 13:04:06 +0200122
Andrey Andreev67ccdc02012-02-27 23:57:58 +0200123 // Append application specific cookie prefix
124 if (config_item('cookie_prefix'))
125 {
126 $this->_csrf_cookie_name = config_item('cookie_prefix').$this->_csrf_cookie_name;
127 }
Derek Jonesb3f10a22010-07-25 19:11:26 -0500128
Andrey Andreev67ccdc02012-02-27 23:57:58 +0200129 // Set the CSRF hash
130 $this->_csrf_set_hash();
131 }
Derek Allard958543a2010-07-22 14:10:26 -0400132
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200133 log_message('debug', 'Security Class Initialized');
Derek Jonese701d762010-03-02 18:17:01 -0600134 }
135
136 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200137
Derek Jonese701d762010-03-02 18:17:01 -0600138 /**
139 * Verify Cross Site Request Forgery Protection
140 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400141 * @return object
Derek Jonese701d762010-03-02 18:17:01 -0600142 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500143 public function csrf_verify()
Derek Allard958543a2010-07-22 14:10:26 -0400144 {
Andrey Andreev5d27c432012-03-08 12:01:52 +0200145 // If it's not a POST request we will set the CSRF cookie
146 if (strtoupper($_SERVER['REQUEST_METHOD']) !== 'POST')
Derek Jonese701d762010-03-02 18:17:01 -0600147 {
148 return $this->csrf_set_cookie();
149 }
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300150
Alex Bilbieaeb2c3e2011-08-21 16:14:54 +0100151 // Check if URI has been whitelisted from CSRF checks
152 if ($exclude_uris = config_item('csrf_exclude_uris'))
153 {
154 $uri = load_class('URI', 'core');
155 if (in_array($uri->uri_string(), $exclude_uris))
156 {
157 return $this;
158 }
159 }
Derek Jonese701d762010-03-02 18:17:01 -0600160
161 // Do the tokens exist in both the _POST and _COOKIE arrays?
Andrey Andreev4562f2c2012-01-09 23:39:50 +0200162 if ( ! isset($_POST[$this->_csrf_token_name]) OR ! isset($_COOKIE[$this->_csrf_cookie_name])
163 OR $_POST[$this->_csrf_token_name] != $_COOKIE[$this->_csrf_cookie_name]) // Do the tokens match?
Derek Jonese701d762010-03-02 18:17:01 -0600164 {
165 $this->csrf_show_error();
166 }
167
Andrey Andreev4562f2c2012-01-09 23:39:50 +0200168 // We kill this since we're done and we don't want to polute the _POST array
Pascal Krietec9c045a2011-04-05 14:50:41 -0400169 unset($_POST[$this->_csrf_token_name]);
Barry Mienydd671972010-10-04 16:33:58 +0200170
RS712be25a62011-12-31 16:02:04 -0200171 // Regenerate on every submission?
172 if (config_item('csrf_regenerate'))
173 {
174 // Nothing should last forever
175 unset($_COOKIE[$this->_csrf_cookie_name]);
176 $this->_csrf_hash = '';
177 }
Andrey Andreev8a7d0782012-01-08 05:43:42 +0200178
Derek Jonesb3f10a22010-07-25 19:11:26 -0500179 $this->_csrf_set_hash();
180 $this->csrf_set_cookie();
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300181
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200182 log_message('debug', 'CSRF token verified');
Pascal Krietec9c045a2011-04-05 14:50:41 -0400183 return $this;
Derek Jonese701d762010-03-02 18:17:01 -0600184 }
Barry Mienydd671972010-10-04 16:33:58 +0200185
Derek Jonese701d762010-03-02 18:17:01 -0600186 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200187
Derek Jonese701d762010-03-02 18:17:01 -0600188 /**
189 * Set Cross Site Request Forgery Protection Cookie
190 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400191 * @return object
Derek Jonese701d762010-03-02 18:17:01 -0600192 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500193 public function csrf_set_cookie()
Derek Jonese701d762010-03-02 18:17:01 -0600194 {
Pascal Krietec9c045a2011-04-05 14:50:41 -0400195 $expire = time() + $this->_csrf_expire;
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300196 $secure_cookie = (bool) config_item('cookie_secure');
Derek Jonese701d762010-03-02 18:17:01 -0600197
Andrey Andreeva10c8e12012-02-29 18:56:12 +0200198 if ($secure_cookie && (empty($_SERVER['HTTPS']) OR strtolower($_SERVER['HTTPS']) === 'off'))
Derek Jonese701d762010-03-02 18:17:01 -0600199 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200200 return FALSE;
Derek Jonese701d762010-03-02 18:17:01 -0600201 }
Derek Allard958543a2010-07-22 14:10:26 -0400202
freewil4ad0fd82012-03-13 22:37:42 -0400203 setcookie(
204 $this->_csrf_cookie_name,
205 $this->_csrf_hash,
206 $expire,
207 config_item('cookie_path'),
208 config_item('cookie_domain'),
209 $secure_cookie,
210 config_item('cookie_httponly')
211 );
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200212 log_message('debug', 'CRSF cookie Set');
David Behler07b53422011-08-15 00:25:06 +0200213
Pascal Krietec9c045a2011-04-05 14:50:41 -0400214 return $this;
Derek Jonese701d762010-03-02 18:17:01 -0600215 }
216
217 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200218
Derek Jonese701d762010-03-02 18:17:01 -0600219 /**
220 * Show CSRF Error
221 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400222 * @return void
Derek Jonese701d762010-03-02 18:17:01 -0600223 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500224 public function csrf_show_error()
Derek Jonese701d762010-03-02 18:17:01 -0600225 {
226 show_error('The action you have requested is not allowed.');
227 }
228
229 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200230
Derek Jonese701d762010-03-02 18:17:01 -0600231 /**
David Behler07b53422011-08-15 00:25:06 +0200232 * Get CSRF Hash
Pascal Krietec9c045a2011-04-05 14:50:41 -0400233 *
David Behler07b53422011-08-15 00:25:06 +0200234 * Getter Method
Pascal Krietec9c045a2011-04-05 14:50:41 -0400235 *
236 * @return string self::_csrf_hash
237 */
238 public function get_csrf_hash()
239 {
240 return $this->_csrf_hash;
241 }
242
243 // --------------------------------------------------------------------
244
245 /**
246 * Get CSRF Token Name
247 *
248 * Getter Method
249 *
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200250 * @return string self::_csrf_token_name
Pascal Krietec9c045a2011-04-05 14:50:41 -0400251 */
252 public function get_csrf_token_name()
253 {
254 return $this->_csrf_token_name;
255 }
256
257 // --------------------------------------------------------------------
258
259 /**
Derek Jonese701d762010-03-02 18:17:01 -0600260 * XSS Clean
261 *
262 * Sanitizes data so that Cross Site Scripting Hacks can be
Derek Jones37f4b9c2011-07-01 17:56:50 -0500263 * prevented. This function does a fair amount of work but
Derek Jonese701d762010-03-02 18:17:01 -0600264 * it is extremely thorough, designed to prevent even the
Derek Jones37f4b9c2011-07-01 17:56:50 -0500265 * most obscure XSS attempts. Nothing is ever 100% foolproof,
Derek Jonese701d762010-03-02 18:17:01 -0600266 * of course, but I haven't been able to get anything passed
267 * the filter.
268 *
269 * Note: This function should only be used to deal with data
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200270 * upon submission. It's not something that should
Derek Jonese701d762010-03-02 18:17:01 -0600271 * be used for general runtime processing.
272 *
273 * This function was based in part on some code and ideas I
274 * got from Bitflux: http://channel.bitflux.ch/wiki/XSS_Prevention
275 *
276 * To help develop this script I used this great list of
277 * vulnerabilities along with a few other hacks I've
278 * harvested from examining vulnerabilities in other programs:
279 * http://ha.ckers.org/xss.html
280 *
Derek Jonese701d762010-03-02 18:17:01 -0600281 * @param mixed string or array
David Behler07b53422011-08-15 00:25:06 +0200282 * @param bool
Derek Jonese701d762010-03-02 18:17:01 -0600283 * @return string
284 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500285 public function xss_clean($str, $is_image = FALSE)
Derek Jonese701d762010-03-02 18:17:01 -0600286 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200287 // Is the string an array?
Derek Jonese701d762010-03-02 18:17:01 -0600288 if (is_array($str))
289 {
290 while (list($key) = each($str))
291 {
292 $str[$key] = $this->xss_clean($str[$key]);
293 }
Barry Mienydd671972010-10-04 16:33:58 +0200294
Derek Jonese701d762010-03-02 18:17:01 -0600295 return $str;
296 }
297
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200298 // Remove Invisible Characters and validate entities in URLs
299 $str = $this->_validate_entities(remove_invisible_characters($str));
Derek Jonese701d762010-03-02 18:17:01 -0600300
301 /*
302 * URL Decode
303 *
304 * Just in case stuff like this is submitted:
305 *
306 * <a href="http://%77%77%77%2E%67%6F%6F%67%6C%65%2E%63%6F%6D">Google</a>
307 *
308 * Note: Use rawurldecode() so it does not remove plus signs
Derek Jonese701d762010-03-02 18:17:01 -0600309 */
310 $str = rawurldecode($str);
Barry Mienydd671972010-10-04 16:33:58 +0200311
Derek Jonese701d762010-03-02 18:17:01 -0600312 /*
Barry Mienydd671972010-10-04 16:33:58 +0200313 * Convert character entities to ASCII
Derek Jonese701d762010-03-02 18:17:01 -0600314 *
315 * This permits our tests below to work reliably.
316 * We only convert entities that are within tags since
317 * these are the ones that will pose security problems.
Derek Jonese701d762010-03-02 18:17:01 -0600318 */
Derek Jonese701d762010-03-02 18:17:01 -0600319 $str = preg_replace_callback("/[a-z]+=([\'\"]).*?\\1/si", array($this, '_convert_attribute'), $str);
Andrey Andreev4562f2c2012-01-09 23:39:50 +0200320 $str = preg_replace_callback('/<\w+.*?(?=>|<|$)/si', array($this, '_decode_entity'), $str);
Derek Jonese701d762010-03-02 18:17:01 -0600321
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200322 // Remove Invisible Characters Again!
Greg Aker757dda62010-04-14 19:06:19 -0500323 $str = remove_invisible_characters($str);
Barry Mienydd671972010-10-04 16:33:58 +0200324
Derek Jonese701d762010-03-02 18:17:01 -0600325 /*
326 * Convert all tabs to spaces
327 *
328 * This prevents strings like this: ja vascript
329 * NOTE: we deal with spaces between characters later.
David Behler07b53422011-08-15 00:25:06 +0200330 * NOTE: preg_replace was found to be amazingly slow here on
Pascal Krietec9c045a2011-04-05 14:50:41 -0400331 * large blocks of data, so we use str_replace.
Derek Jonese701d762010-03-02 18:17:01 -0600332 */
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200333 $str = str_replace("\t", ' ', $str);
Barry Mienydd671972010-10-04 16:33:58 +0200334
Andrey Andreev4562f2c2012-01-09 23:39:50 +0200335 // Capture converted string for later comparison
Derek Jonese701d762010-03-02 18:17:01 -0600336 $converted_string = $str;
Barry Mienydd671972010-10-04 16:33:58 +0200337
Pascal Krietec9c045a2011-04-05 14:50:41 -0400338 // Remove Strings that are never allowed
339 $str = $this->_do_never_allowed($str);
Derek Jonese701d762010-03-02 18:17:01 -0600340
341 /*
342 * Makes PHP tags safe
343 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400344 * Note: XML tags are inadvertently replaced too:
Derek Jonese701d762010-03-02 18:17:01 -0600345 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400346 * <?xml
Derek Jonese701d762010-03-02 18:17:01 -0600347 *
348 * But it doesn't seem to pose a problem.
Derek Jonese701d762010-03-02 18:17:01 -0600349 */
350 if ($is_image === TRUE)
351 {
David Behler07b53422011-08-15 00:25:06 +0200352 // Images have a tendency to have the PHP short opening and
353 // closing tags every so often so we skip those and only
Pascal Krietec9c045a2011-04-05 14:50:41 -0400354 // do the long opening tags.
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200355 $str = preg_replace('/<\?(php)/i', '&lt;?\\1', $str);
Derek Jonese701d762010-03-02 18:17:01 -0600356 }
357 else
358 {
Derek Jones37f4b9c2011-07-01 17:56:50 -0500359 $str = str_replace(array('<?', '?'.'>'), array('&lt;?', '?&gt;'), $str);
Derek Jonese701d762010-03-02 18:17:01 -0600360 }
Barry Mienydd671972010-10-04 16:33:58 +0200361
Derek Jonese701d762010-03-02 18:17:01 -0600362 /*
363 * Compact any exploded words
364 *
Derek Jones37f4b9c2011-07-01 17:56:50 -0500365 * This corrects words like: j a v a s c r i p t
Derek Jonese701d762010-03-02 18:17:01 -0600366 * These words are compacted back to their correct state.
Derek Jonese701d762010-03-02 18:17:01 -0600367 */
Pascal Krietec9c045a2011-04-05 14:50:41 -0400368 $words = array(
Wes Bakerd3481352012-05-07 16:49:33 -0400369 'javascript', 'expression', 'vbscript', 'script', 'base64',
Timothy Warren40403d22012-04-19 16:38:50 -0400370 'applet', 'alert', 'document', 'write', 'cookie', 'window'
371 );
David Behler07b53422011-08-15 00:25:06 +0200372
Derek Jones37f4b9c2011-07-01 17:56:50 -0500373
Derek Jonese701d762010-03-02 18:17:01 -0600374 foreach ($words as $word)
375 {
Andrey Andreev67ccdc02012-02-27 23:57:58 +0200376 $word = implode('\s*', str_split($word)).'\s*';
Derek Jonese701d762010-03-02 18:17:01 -0600377
378 // We only want to do this when it is followed by a non-word character
379 // That way valid stuff like "dealer to" does not become "dealerto"
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300380 $str = preg_replace_callback('#('.substr($word, 0, -3).')(\W)#is', array($this, '_compact_exploded_words'), $str);
Derek Jonese701d762010-03-02 18:17:01 -0600381 }
Barry Mienydd671972010-10-04 16:33:58 +0200382
Derek Jonese701d762010-03-02 18:17:01 -0600383 /*
384 * Remove disallowed Javascript in links or img tags
David Behler07b53422011-08-15 00:25:06 +0200385 * We used to do some version comparisons and use of stripos for PHP5,
386 * but it is dog slow compared to these simplified non-capturing
Pascal Krietec9c045a2011-04-05 14:50:41 -0400387 * preg_match(), especially if the pattern exists in the string
Derek Jonese701d762010-03-02 18:17:01 -0600388 */
389 do
390 {
391 $original = $str;
Barry Mienydd671972010-10-04 16:33:58 +0200392
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200393 if (preg_match('/<a/i', $str))
Derek Jonese701d762010-03-02 18:17:01 -0600394 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200395 $str = preg_replace_callback('#<a\s+([^>]*?)(>|$)#si', array($this, '_js_link_removal'), $str);
Derek Jonese701d762010-03-02 18:17:01 -0600396 }
Barry Mienydd671972010-10-04 16:33:58 +0200397
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200398 if (preg_match('/<img/i', $str))
Derek Jonese701d762010-03-02 18:17:01 -0600399 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200400 $str = preg_replace_callback('#<img\s+([^>]*?)(\s?/?>|$)#si', array($this, '_js_img_removal'), $str);
Derek Jonese701d762010-03-02 18:17:01 -0600401 }
Barry Mienydd671972010-10-04 16:33:58 +0200402
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200403 if (preg_match('/(script|xss)/i', $str))
Derek Jonese701d762010-03-02 18:17:01 -0600404 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200405 $str = preg_replace('#<(/*)(script|xss)(.*?)\>#si', '[removed]', $str);
Derek Jonese701d762010-03-02 18:17:01 -0600406 }
407 }
Pascal Krietec9c045a2011-04-05 14:50:41 -0400408 while($original != $str);
Derek Jonese701d762010-03-02 18:17:01 -0600409
410 unset($original);
411
Pascal Krietec9c045a2011-04-05 14:50:41 -0400412 // Remove evil attributes such as style, onclick and xmlns
413 $str = $this->_remove_evil_attributes($str, $is_image);
Barry Mienydd671972010-10-04 16:33:58 +0200414
Derek Jonese701d762010-03-02 18:17:01 -0600415 /*
416 * Sanitize naughty HTML elements
417 *
418 * If a tag containing any of the words in the list
419 * below is found, the tag gets converted to entities.
420 *
421 * So this: <blink>
422 * Becomes: &lt;blink&gt;
Derek Jonese701d762010-03-02 18:17:01 -0600423 */
424 $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';
425 $str = preg_replace_callback('#<(/*\s*)('.$naughty.')([^><]*)([><]*)#is', array($this, '_sanitize_naughty_html'), $str);
426
427 /*
428 * Sanitize naughty scripting elements
429 *
430 * Similar to above, only instead of looking for
431 * tags it looks for PHP and JavaScript commands
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200432 * that are disallowed. Rather than removing the
Derek Jonese701d762010-03-02 18:17:01 -0600433 * code, it simply converts the parenthesis to entities
434 * rendering the code un-executable.
435 *
436 * For example: eval('some code')
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200437 * Becomes: eval&#40;'some code'&#41;
Derek Jonese701d762010-03-02 18:17:01 -0600438 */
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200439 $str = preg_replace('#(alert|cmd|passthru|eval|exec|expression|system|fopen|fsockopen|file|file_get_contents|readfile|unlink)(\s*)\((.*?)\)#si',
440 '\\1\\2&#40;\\3&#41;',
441 $str);
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 */
Derek Jonese701d762010-03-02 18:17:01 -0600457 if ($is_image === TRUE)
458 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200459 return ($str === $converted_string);
Derek Jonese701d762010-03-02 18:17:01 -0600460 }
Barry Mienydd671972010-10-04 16:33:58 +0200461
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200462 log_message('debug', 'XSS Filtering completed');
Derek Jonese701d762010-03-02 18:17:01 -0600463 return $str;
464 }
465
466 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200467
Derek Jonese701d762010-03-02 18:17:01 -0600468 /**
469 * Random Hash for protecting URLs
470 *
Derek Jonese701d762010-03-02 18:17:01 -0600471 * @return string
472 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500473 public function xss_hash()
Barry Mienydd671972010-10-04 16:33:58 +0200474 {
Pascal Krietec9c045a2011-04-05 14:50:41 -0400475 if ($this->_xss_hash == '')
Derek Jonese701d762010-03-02 18:17:01 -0600476 {
Pascal Krietec38e3b62011-11-14 13:55:00 -0500477 mt_srand();
Pascal Krietec9c045a2011-04-05 14:50:41 -0400478 $this->_xss_hash = md5(time() + mt_rand(0, 1999999999));
Derek Jonese701d762010-03-02 18:17:01 -0600479 }
480
Pascal Krietec9c045a2011-04-05 14:50:41 -0400481 return $this->_xss_hash;
Derek Jonese701d762010-03-02 18:17:01 -0600482 }
483
484 // --------------------------------------------------------------------
485
486 /**
Derek Jonesa0911472010-03-30 10:33:09 -0500487 * HTML Entities Decode
488 *
489 * This function is a replacement for html_entity_decode()
490 *
Pascal Krietec38e3b62011-11-14 13:55:00 -0500491 * The reason we are not using html_entity_decode() by itself is because
492 * while it is not technically correct to leave out the semicolon
493 * at the end of an entity most browsers will still interpret the entity
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200494 * correctly. html_entity_decode() does not convert entities without
Pascal Krietec38e3b62011-11-14 13:55:00 -0500495 * semicolons, so we are left with our own little solution here. Bummer.
Derek Jonesa0911472010-03-30 10:33:09 -0500496 *
Derek Jonesa0911472010-03-30 10:33:09 -0500497 * @param string
498 * @param string
499 * @return string
500 */
freewil8cc0cfe2011-08-27 21:53:00 -0400501 public function entity_decode($str, $charset = NULL)
Derek Jonesa0911472010-03-30 10:33:09 -0500502 {
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300503 if (strpos($str, '&') === FALSE)
freewil5c9b0d12011-08-28 12:15:23 -0400504 {
505 return $str;
506 }
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300507
freewil5c9b0d12011-08-28 12:15:23 -0400508 if (empty($charset))
509 {
510 $charset = config_item('charset');
511 }
Barry Mienydd671972010-10-04 16:33:58 +0200512
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300513 $str = html_entity_decode($str, ENT_COMPAT, $charset);
514 $str = preg_replace('~&#x(0*[0-9a-f]{2,5})~ei', 'chr(hexdec("\\1"))', $str);
515 return preg_replace('~&#([0-9]{2,4})~e', 'chr(\\1)', $str);
Derek Jonesa0911472010-03-30 10:33:09 -0500516 }
Barry Mienydd671972010-10-04 16:33:58 +0200517
Derek Jonesa0911472010-03-30 10:33:09 -0500518 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200519
Derek Jonesa0911472010-03-30 10:33:09 -0500520 /**
Derek Jonese701d762010-03-02 18:17:01 -0600521 * Filename Security
522 *
Derek Jonese701d762010-03-02 18:17:01 -0600523 * @param string
David Behler07b53422011-08-15 00:25:06 +0200524 * @param bool
Derek Jonese701d762010-03-02 18:17:01 -0600525 * @return string
526 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500527 public function sanitize_filename($str, $relative_path = FALSE)
Derek Jonese701d762010-03-02 18:17:01 -0600528 {
529 $bad = array(
Timothy Warren40403d22012-04-19 16:38:50 -0400530 '../', '<!--', '-->', '<', '>',
531 "'", '"', '&', '$', '#',
532 '{', '}', '[', ']', '=',
533 ';', '?', '%20', '%22',
534 '%3c', // <
535 '%253c', // <
536 '%3e', // >
537 '%0e', // >
538 '%28', // (
539 '%29', // )
540 '%2528', // (
541 '%26', // &
542 '%24', // $
543 '%3f', // ?
544 '%3b', // ;
545 '%3d' // =
546 );
David Behler07b53422011-08-15 00:25:06 +0200547
Derek Jones2ef37592010-10-06 17:51:59 -0500548 if ( ! $relative_path)
549 {
550 $bad[] = './';
551 $bad[] = '/';
552 }
Derek Jonese701d762010-03-02 18:17:01 -0600553
Pascal Krietec9c045a2011-04-05 14:50:41 -0400554 $str = remove_invisible_characters($str, FALSE);
Derek Jonese701d762010-03-02 18:17:01 -0600555 return stripslashes(str_replace($bad, '', $str));
556 }
557
Pascal Krietec9c045a2011-04-05 14:50:41 -0400558 // ----------------------------------------------------------------
559
560 /**
561 * Compact Exploded Words
562 *
563 * Callback function for xss_clean() to remove whitespace from
564 * things like j a v a s c r i p t
565 *
Timothy Warrenad475052012-04-19 13:21:06 -0400566 * @param array
567 * @return string
Pascal Krietec9c045a2011-04-05 14:50:41 -0400568 */
569 protected function _compact_exploded_words($matches)
570 {
571 return preg_replace('/\s+/s', '', $matches[1]).$matches[2];
572 }
573
574 // --------------------------------------------------------------------
David Behler07b53422011-08-15 00:25:06 +0200575
Timothy Warrenad475052012-04-19 13:21:06 -0400576 /**
577 * Remove Evil HTML Attributes (like event handlers and style)
Pascal Krietec9c045a2011-04-05 14:50:41 -0400578 *
579 * It removes the evil attribute and either:
580 * - Everything up until a space
581 * For example, everything between the pipes:
582 * <a |style=document.write('hello');alert('world');| class=link>
David Behler07b53422011-08-15 00:25:06 +0200583 * - Everything inside the quotes
Pascal Krietec9c045a2011-04-05 14:50:41 -0400584 * For example, everything between the pipes:
585 * <a |style="document.write('hello'); alert('world');"| class="link">
586 *
587 * @param string $str The string to check
588 * @param boolean $is_image TRUE if this is an image
589 * @return string The string with the evil attributes removed
590 */
591 protected function _remove_evil_attributes($str, $is_image)
592 {
593 // All javascript event handlers (e.g. onload, onclick, onmouseover), style, and xmlns
Pascal Krietec38e3b62011-11-14 13:55:00 -0500594 $evil_attributes = array('on\w*', 'style', 'xmlns', 'formaction');
Pascal Krietec9c045a2011-04-05 14:50:41 -0400595
596 if ($is_image === TRUE)
597 {
598 /*
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200599 * Adobe Photoshop puts XML metadata into JFIF images,
Pascal Krietec9c045a2011-04-05 14:50:41 -0400600 * including namespacing, so we have to allow this for images.
601 */
602 unset($evil_attributes[array_search('xmlns', $evil_attributes)]);
603 }
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200604
Pascal Krietec9c045a2011-04-05 14:50:41 -0400605 do {
Pascal Krietec38e3b62011-11-14 13:55:00 -0500606 $count = 0;
607 $attribs = array();
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200608
Pascal Krietec38e3b62011-11-14 13:55:00 -0500609 // find occurrences of illegal attribute strings without quotes
Wes Baker5335bc32012-04-24 15:17:14 -0400610 preg_match_all('/('.implode('|', $evil_attributes).')\s*=\s*([^\s>]*)/is', $str, $matches, PREG_SET_ORDER);
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200611
Pascal Krietec38e3b62011-11-14 13:55:00 -0500612 foreach ($matches as $attr)
613 {
Wes Baker5335bc32012-04-24 15:17:14 -0400614
Pascal Krietec38e3b62011-11-14 13:55:00 -0500615 $attribs[] = preg_quote($attr[0], '/');
616 }
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200617
Pascal Krietec38e3b62011-11-14 13:55:00 -0500618 // find occurrences of illegal attribute strings with quotes (042 and 047 are octal quotes)
Andrey Andreev67ccdc02012-02-27 23:57:58 +0200619 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 +0200620
Pascal Krietec38e3b62011-11-14 13:55:00 -0500621 foreach ($matches as $attr)
622 {
623 $attribs[] = preg_quote($attr[0], '/');
624 }
625
626 // replace illegal attribute strings that are inside an html tag
627 if (count($attribs) > 0)
628 {
Wes Baker5335bc32012-04-24 15:17:14 -0400629 $str = preg_replace("/<(\/?[^><]+?)([^A-Za-z<>\-])(.*?)(".implode('|', $attribs).")(.*?)([\s><])([><]*)/i", '<$1 $3$5$6$7', $str, -1, $count);
Pascal Krietec38e3b62011-11-14 13:55:00 -0500630 }
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200631
Pascal Krietec38e3b62011-11-14 13:55:00 -0500632 } while ($count);
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200633
Pascal Krietec9c045a2011-04-05 14:50:41 -0400634 return $str;
635 }
David Behler07b53422011-08-15 00:25:06 +0200636
Pascal Krietec9c045a2011-04-05 14:50:41 -0400637 // --------------------------------------------------------------------
638
639 /**
640 * Sanitize Naughty HTML
641 *
642 * Callback function for xss_clean() to remove naughty HTML elements
643 *
644 * @param array
645 * @return string
646 */
647 protected function _sanitize_naughty_html($matches)
648 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200649 return '&lt;'.$matches[1].$matches[2].$matches[3] // encode opening brace
650 // encode captured opening or closing brace to prevent recursive vectors:
Andrey Andreev67ccdc02012-02-27 23:57:58 +0200651 .str_replace(array('>', '<'), array('&gt;', '&lt;'), $matches[4]);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400652 }
653
654 // --------------------------------------------------------------------
655
656 /**
657 * JS Link Removal
658 *
659 * Callback function for xss_clean() to sanitize links
660 * This limits the PCRE backtracks, making it more performance friendly
661 * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in
662 * PHP 5.2+ on link-heavy strings
663 *
664 * @param array
665 * @return string
666 */
667 protected function _js_link_removal($match)
668 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200669 return str_replace($match[1],
Wes Baker5335bc32012-04-24 15:17:14 -0400670 preg_replace('#href=.*?(alert\(|alert&\#40;|javascript\:|livescript\:|mocha\:|charset\=|window\.|document\.|\.cookie|<script|<xss|data\s*:)#si',
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200671 '',
672 $this->_filter_attributes(str_replace(array('<', '>'), '', $match[1]))
673 ),
674 $match[0]);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400675 }
676
677 // --------------------------------------------------------------------
678
679 /**
680 * JS Image Removal
681 *
682 * Callback function for xss_clean() to sanitize image tags
683 * This limits the PCRE backtracks, making it more performance friendly
684 * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in
685 * PHP 5.2+ on image tag heavy strings
686 *
687 * @param array
688 * @return string
689 */
690 protected function _js_img_removal($match)
691 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200692 return str_replace($match[1],
693 preg_replace('#src=.*?(alert\(|alert&\#40;|javascript\:|livescript\:|mocha\:|charset\=|window\.|document\.|\.cookie|<script|<xss|base64\s*,)#si',
694 '',
695 $this->_filter_attributes(str_replace(array('<', '>'), '', $match[1]))
696 ),
697 $match[0]);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400698 }
699
700 // --------------------------------------------------------------------
701
702 /**
703 * Attribute Conversion
704 *
705 * Used as a callback for XSS Clean
706 *
707 * @param array
708 * @return string
709 */
710 protected function _convert_attribute($match)
711 {
712 return str_replace(array('>', '<', '\\'), array('&gt;', '&lt;', '\\\\'), $match[0]);
713 }
714
715 // --------------------------------------------------------------------
716
717 /**
718 * Filter Attributes
719 *
720 * Filters tag attributes for consistency and safety
721 *
722 * @param string
723 * @return string
724 */
725 protected function _filter_attributes($str)
726 {
727 $out = '';
Pascal Krietec9c045a2011-04-05 14:50:41 -0400728 if (preg_match_all('#\s*[a-z\-]+\s*=\s*(\042|\047)([^\\1]*?)\\1#is', $str, $matches))
729 {
730 foreach ($matches[0] as $match)
731 {
Andrey Andreev4562f2c2012-01-09 23:39:50 +0200732 $out .= preg_replace('#/\*.*?\*/#s', '', $match);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400733 }
734 }
735
736 return $out;
737 }
738
739 // --------------------------------------------------------------------
740
741 /**
742 * HTML Entity Decode Callback
743 *
744 * Used as a callback for XSS Clean
745 *
746 * @param array
747 * @return string
748 */
749 protected function _decode_entity($match)
750 {
751 return $this->entity_decode($match[0], strtoupper(config_item('charset')));
752 }
753
754 // --------------------------------------------------------------------
David Behler07b53422011-08-15 00:25:06 +0200755
Pascal Krietec9c045a2011-04-05 14:50:41 -0400756 /**
757 * Validate URL entities
758 *
759 * Called by xss_clean()
760 *
David Behler07b53422011-08-15 00:25:06 +0200761 * @param string
Pascal Krietec9c045a2011-04-05 14:50:41 -0400762 * @return string
763 */
764 protected function _validate_entities($str)
765 {
766 /*
767 * Protect GET variables in URLs
768 */
David Behler07b53422011-08-15 00:25:06 +0200769
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200770 // 901119URL5918AMP18930PROTECT8198
771 $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 -0400772
773 /*
774 * Validate standard character entities
775 *
Derek Jones37f4b9c2011-07-01 17:56:50 -0500776 * Add a semicolon if missing. We do this to enable
Pascal Krietec9c045a2011-04-05 14:50:41 -0400777 * the conversion of entities to ASCII later.
Pascal Krietec9c045a2011-04-05 14:50:41 -0400778 */
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200779 $str = preg_replace('#(&\#?[0-9a-z]{2,})([\x00-\x20])*;?#i', '\\1;\\2', $str);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400780
781 /*
782 * Validate UTF16 two byte encoding (x00)
783 *
784 * Just as above, adds a semicolon if missing.
Pascal Krietec9c045a2011-04-05 14:50:41 -0400785 */
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200786 $str = preg_replace('#(&\#x?)([0-9A-F]+);?#i', '\\1\\2;', $str);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400787
788 /*
789 * Un-Protect GET variables in URLs
790 */
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200791 return str_replace($this->xss_hash(), '&', $str);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400792 }
793
794 // ----------------------------------------------------------------------
795
796 /**
797 * Do Never Allowed
798 *
799 * A utility function for xss_clean()
800 *
801 * @param string
802 * @return string
803 */
804 protected function _do_never_allowed($str)
805 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200806 $str = str_replace(array_keys($this->_never_allowed_str), $this->_never_allowed_str, $str);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400807
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200808 foreach ($this->_never_allowed_regex as $regex)
Pascal Krietec9c045a2011-04-05 14:50:41 -0400809 {
Wes Baker5335bc32012-04-24 15:17:14 -0400810 $str = preg_replace('#'.$regex.'#is', '[removed]', $str);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400811 }
David Behler07b53422011-08-15 00:25:06 +0200812
Pascal Krietec9c045a2011-04-05 14:50:41 -0400813 return $str;
814 }
815
816 // --------------------------------------------------------------------
817
818 /**
819 * Set Cross Site Request Forgery Protection Cookie
820 *
821 * @return string
822 */
823 protected function _csrf_set_hash()
824 {
825 if ($this->_csrf_hash == '')
826 {
David Behler07b53422011-08-15 00:25:06 +0200827 // If the cookie exists we will use it's value.
Pascal Krietec9c045a2011-04-05 14:50:41 -0400828 // We don't necessarily want to regenerate it with
David Behler07b53422011-08-15 00:25:06 +0200829 // each page load since a page could contain embedded
Pascal Krietec9c045a2011-04-05 14:50:41 -0400830 // sub-pages causing this feature to fail
David Behler07b53422011-08-15 00:25:06 +0200831 if (isset($_COOKIE[$this->_csrf_cookie_name]) &&
Pascal Krietec9c045a2011-04-05 14:50:41 -0400832 $_COOKIE[$this->_csrf_cookie_name] != '')
833 {
834 return $this->_csrf_hash = $_COOKIE[$this->_csrf_cookie_name];
835 }
David Behler07b53422011-08-15 00:25:06 +0200836
Chris Berthed93e6f32011-09-25 10:33:25 -0400837 $this->_csrf_hash = md5(uniqid(rand(), TRUE));
838 $this->csrf_set_cookie();
Pascal Krietec9c045a2011-04-05 14:50:41 -0400839 }
840
841 return $this->_csrf_hash;
842 }
843
Derek Jonese701d762010-03-02 18:17:01 -0600844}
Derek Jonese701d762010-03-02 18:17:01 -0600845
846/* End of file Security.php */
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200847/* Location: ./system/core/Security.php */