blob: 9b7ba57991b4418f4d0095d0cf5b3fa1b91a96ec [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 );
Andrey Andreev92ebfb62012-05-17 12:49:24 +0300105
Timothy Warrenad475052012-04-19 13:21:06 -0400106 /**
107 * Initialize security class
Andrey Andreev92ebfb62012-05-17 12:49:24 +0300108 *
109 * @return void
Timothy Warrenad475052012-04-19 13:21:06 -0400110 */
Greg Akera9263282010-11-10 15:26:43 -0600111 public function __construct()
Derek Jonese701d762010-03-02 18:17:01 -0600112 {
Andrey Andreev67ccdc02012-02-27 23:57:58 +0200113 // Is CSRF protection enabled?
114 if (config_item('csrf_protection') === TRUE)
patworkef1a55a2011-04-09 13:04:06 +0200115 {
Andrey Andreev67ccdc02012-02-27 23:57:58 +0200116 // CSRF config
117 foreach (array('csrf_expire', 'csrf_token_name', 'csrf_cookie_name') as $key)
patworkef1a55a2011-04-09 13:04:06 +0200118 {
Andrey Andreev67ccdc02012-02-27 23:57:58 +0200119 if (FALSE !== ($val = config_item($key)))
120 {
121 $this->{'_'.$key} = $val;
122 }
patworkef1a55a2011-04-09 13:04:06 +0200123 }
patworkef1a55a2011-04-09 13:04:06 +0200124
Andrey Andreev67ccdc02012-02-27 23:57:58 +0200125 // Append application specific cookie prefix
126 if (config_item('cookie_prefix'))
127 {
128 $this->_csrf_cookie_name = config_item('cookie_prefix').$this->_csrf_cookie_name;
129 }
Derek Jonesb3f10a22010-07-25 19:11:26 -0500130
Andrey Andreev67ccdc02012-02-27 23:57:58 +0200131 // Set the CSRF hash
132 $this->_csrf_set_hash();
133 }
Derek Allard958543a2010-07-22 14:10:26 -0400134
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200135 log_message('debug', 'Security Class Initialized');
Derek Jonese701d762010-03-02 18:17:01 -0600136 }
137
138 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200139
Derek Jonese701d762010-03-02 18:17:01 -0600140 /**
141 * Verify Cross Site Request Forgery Protection
142 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400143 * @return object
Derek Jonese701d762010-03-02 18:17:01 -0600144 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500145 public function csrf_verify()
Derek Allard958543a2010-07-22 14:10:26 -0400146 {
Andrey Andreev5d27c432012-03-08 12:01:52 +0200147 // If it's not a POST request we will set the CSRF cookie
148 if (strtoupper($_SERVER['REQUEST_METHOD']) !== 'POST')
Derek Jonese701d762010-03-02 18:17:01 -0600149 {
150 return $this->csrf_set_cookie();
151 }
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300152
Alex Bilbieaeb2c3e2011-08-21 16:14:54 +0100153 // Check if URI has been whitelisted from CSRF checks
154 if ($exclude_uris = config_item('csrf_exclude_uris'))
155 {
156 $uri = load_class('URI', 'core');
157 if (in_array($uri->uri_string(), $exclude_uris))
158 {
159 return $this;
160 }
161 }
Derek Jonese701d762010-03-02 18:17:01 -0600162
163 // Do the tokens exist in both the _POST and _COOKIE arrays?
Andrey Andreev4562f2c2012-01-09 23:39:50 +0200164 if ( ! isset($_POST[$this->_csrf_token_name]) OR ! isset($_COOKIE[$this->_csrf_cookie_name])
165 OR $_POST[$this->_csrf_token_name] != $_COOKIE[$this->_csrf_cookie_name]) // Do the tokens match?
Derek Jonese701d762010-03-02 18:17:01 -0600166 {
167 $this->csrf_show_error();
168 }
169
Andrey Andreev4562f2c2012-01-09 23:39:50 +0200170 // We kill this since we're done and we don't want to polute the _POST array
Pascal Krietec9c045a2011-04-05 14:50:41 -0400171 unset($_POST[$this->_csrf_token_name]);
Barry Mienydd671972010-10-04 16:33:58 +0200172
RS712be25a62011-12-31 16:02:04 -0200173 // Regenerate on every submission?
174 if (config_item('csrf_regenerate'))
175 {
176 // Nothing should last forever
177 unset($_COOKIE[$this->_csrf_cookie_name]);
178 $this->_csrf_hash = '';
179 }
Andrey Andreev8a7d0782012-01-08 05:43:42 +0200180
Derek Jonesb3f10a22010-07-25 19:11:26 -0500181 $this->_csrf_set_hash();
182 $this->csrf_set_cookie();
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300183
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200184 log_message('debug', 'CSRF token verified');
Pascal Krietec9c045a2011-04-05 14:50:41 -0400185 return $this;
Derek Jonese701d762010-03-02 18:17:01 -0600186 }
Barry Mienydd671972010-10-04 16:33:58 +0200187
Derek Jonese701d762010-03-02 18:17:01 -0600188 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200189
Derek Jonese701d762010-03-02 18:17:01 -0600190 /**
191 * Set Cross Site Request Forgery Protection Cookie
192 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400193 * @return object
Taufan Aditya6c7526c2012-05-27 13:51:27 +0700194 * @codeCoverageIgnore
Derek Jonese701d762010-03-02 18:17:01 -0600195 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500196 public function csrf_set_cookie()
Derek Jonese701d762010-03-02 18:17:01 -0600197 {
Pascal Krietec9c045a2011-04-05 14:50:41 -0400198 $expire = time() + $this->_csrf_expire;
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300199 $secure_cookie = (bool) config_item('cookie_secure');
Derek Jonese701d762010-03-02 18:17:01 -0600200
Andrey Andreeva10c8e12012-02-29 18:56:12 +0200201 if ($secure_cookie && (empty($_SERVER['HTTPS']) OR strtolower($_SERVER['HTTPS']) === 'off'))
Derek Jonese701d762010-03-02 18:17:01 -0600202 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200203 return FALSE;
Derek Jonese701d762010-03-02 18:17:01 -0600204 }
Derek Allard958543a2010-07-22 14:10:26 -0400205
freewil4ad0fd82012-03-13 22:37:42 -0400206 setcookie(
Andrey Andreev92ebfb62012-05-17 12:49:24 +0300207 $this->_csrf_cookie_name,
208 $this->_csrf_hash,
209 $expire,
210 config_item('cookie_path'),
211 config_item('cookie_domain'),
freewil4ad0fd82012-03-13 22:37:42 -0400212 $secure_cookie,
213 config_item('cookie_httponly')
214 );
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200215 log_message('debug', 'CRSF cookie Set');
David Behler07b53422011-08-15 00:25:06 +0200216
Pascal Krietec9c045a2011-04-05 14:50:41 -0400217 return $this;
Derek Jonese701d762010-03-02 18:17:01 -0600218 }
219
220 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200221
Derek Jonese701d762010-03-02 18:17:01 -0600222 /**
223 * Show CSRF Error
224 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400225 * @return void
Derek Jonese701d762010-03-02 18:17:01 -0600226 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500227 public function csrf_show_error()
Derek Jonese701d762010-03-02 18:17:01 -0600228 {
229 show_error('The action you have requested is not allowed.');
230 }
231
232 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200233
Derek Jonese701d762010-03-02 18:17:01 -0600234 /**
David Behler07b53422011-08-15 00:25:06 +0200235 * Get CSRF Hash
Pascal Krietec9c045a2011-04-05 14:50:41 -0400236 *
David Behler07b53422011-08-15 00:25:06 +0200237 * Getter Method
Pascal Krietec9c045a2011-04-05 14:50:41 -0400238 *
239 * @return string self::_csrf_hash
240 */
241 public function get_csrf_hash()
242 {
243 return $this->_csrf_hash;
244 }
245
246 // --------------------------------------------------------------------
247
248 /**
249 * Get CSRF Token Name
250 *
251 * Getter Method
252 *
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200253 * @return string self::_csrf_token_name
Pascal Krietec9c045a2011-04-05 14:50:41 -0400254 */
255 public function get_csrf_token_name()
256 {
257 return $this->_csrf_token_name;
258 }
259
260 // --------------------------------------------------------------------
261
262 /**
Derek Jonese701d762010-03-02 18:17:01 -0600263 * XSS Clean
264 *
265 * Sanitizes data so that Cross Site Scripting Hacks can be
Derek Jones37f4b9c2011-07-01 17:56:50 -0500266 * prevented. This function does a fair amount of work but
Derek Jonese701d762010-03-02 18:17:01 -0600267 * it is extremely thorough, designed to prevent even the
Derek Jones37f4b9c2011-07-01 17:56:50 -0500268 * most obscure XSS attempts. Nothing is ever 100% foolproof,
Derek Jonese701d762010-03-02 18:17:01 -0600269 * of course, but I haven't been able to get anything passed
270 * the filter.
271 *
272 * Note: This function should only be used to deal with data
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200273 * upon submission. It's not something that should
Derek Jonese701d762010-03-02 18:17:01 -0600274 * be used for general runtime processing.
275 *
276 * This function was based in part on some code and ideas I
277 * got from Bitflux: http://channel.bitflux.ch/wiki/XSS_Prevention
278 *
279 * To help develop this script I used this great list of
280 * vulnerabilities along with a few other hacks I've
281 * harvested from examining vulnerabilities in other programs:
282 * http://ha.ckers.org/xss.html
283 *
Derek Jonese701d762010-03-02 18:17:01 -0600284 * @param mixed string or array
David Behler07b53422011-08-15 00:25:06 +0200285 * @param bool
Derek Jonese701d762010-03-02 18:17:01 -0600286 * @return string
287 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500288 public function xss_clean($str, $is_image = FALSE)
Derek Jonese701d762010-03-02 18:17:01 -0600289 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200290 // Is the string an array?
Derek Jonese701d762010-03-02 18:17:01 -0600291 if (is_array($str))
292 {
293 while (list($key) = each($str))
294 {
295 $str[$key] = $this->xss_clean($str[$key]);
296 }
Barry Mienydd671972010-10-04 16:33:58 +0200297
Derek Jonese701d762010-03-02 18:17:01 -0600298 return $str;
299 }
300
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200301 // Remove Invisible Characters and validate entities in URLs
302 $str = $this->_validate_entities(remove_invisible_characters($str));
Derek Jonese701d762010-03-02 18:17:01 -0600303
304 /*
305 * URL Decode
306 *
307 * Just in case stuff like this is submitted:
308 *
309 * <a href="http://%77%77%77%2E%67%6F%6F%67%6C%65%2E%63%6F%6D">Google</a>
310 *
311 * Note: Use rawurldecode() so it does not remove plus signs
Derek Jonese701d762010-03-02 18:17:01 -0600312 */
313 $str = rawurldecode($str);
Barry Mienydd671972010-10-04 16:33:58 +0200314
Derek Jonese701d762010-03-02 18:17:01 -0600315 /*
Barry Mienydd671972010-10-04 16:33:58 +0200316 * Convert character entities to ASCII
Derek Jonese701d762010-03-02 18:17:01 -0600317 *
318 * This permits our tests below to work reliably.
319 * We only convert entities that are within tags since
320 * these are the ones that will pose security problems.
Derek Jonese701d762010-03-02 18:17:01 -0600321 */
Derek Jonese701d762010-03-02 18:17:01 -0600322 $str = preg_replace_callback("/[a-z]+=([\'\"]).*?\\1/si", array($this, '_convert_attribute'), $str);
Andrey Andreev4562f2c2012-01-09 23:39:50 +0200323 $str = preg_replace_callback('/<\w+.*?(?=>|<|$)/si', array($this, '_decode_entity'), $str);
Derek Jonese701d762010-03-02 18:17:01 -0600324
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200325 // Remove Invisible Characters Again!
Greg Aker757dda62010-04-14 19:06:19 -0500326 $str = remove_invisible_characters($str);
Barry Mienydd671972010-10-04 16:33:58 +0200327
Derek Jonese701d762010-03-02 18:17:01 -0600328 /*
329 * Convert all tabs to spaces
330 *
331 * This prevents strings like this: ja vascript
332 * NOTE: we deal with spaces between characters later.
David Behler07b53422011-08-15 00:25:06 +0200333 * NOTE: preg_replace was found to be amazingly slow here on
Pascal Krietec9c045a2011-04-05 14:50:41 -0400334 * large blocks of data, so we use str_replace.
Derek Jonese701d762010-03-02 18:17:01 -0600335 */
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200336 $str = str_replace("\t", ' ', $str);
Barry Mienydd671972010-10-04 16:33:58 +0200337
Andrey Andreev4562f2c2012-01-09 23:39:50 +0200338 // Capture converted string for later comparison
Derek Jonese701d762010-03-02 18:17:01 -0600339 $converted_string = $str;
Barry Mienydd671972010-10-04 16:33:58 +0200340
Pascal Krietec9c045a2011-04-05 14:50:41 -0400341 // Remove Strings that are never allowed
342 $str = $this->_do_never_allowed($str);
Derek Jonese701d762010-03-02 18:17:01 -0600343
344 /*
345 * Makes PHP tags safe
346 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400347 * Note: XML tags are inadvertently replaced too:
Derek Jonese701d762010-03-02 18:17:01 -0600348 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400349 * <?xml
Derek Jonese701d762010-03-02 18:17:01 -0600350 *
351 * But it doesn't seem to pose a problem.
Derek Jonese701d762010-03-02 18:17:01 -0600352 */
353 if ($is_image === TRUE)
354 {
David Behler07b53422011-08-15 00:25:06 +0200355 // Images have a tendency to have the PHP short opening and
356 // closing tags every so often so we skip those and only
Pascal Krietec9c045a2011-04-05 14:50:41 -0400357 // do the long opening tags.
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200358 $str = preg_replace('/<\?(php)/i', '&lt;?\\1', $str);
Derek Jonese701d762010-03-02 18:17:01 -0600359 }
360 else
361 {
Derek Jones37f4b9c2011-07-01 17:56:50 -0500362 $str = str_replace(array('<?', '?'.'>'), array('&lt;?', '?&gt;'), $str);
Derek Jonese701d762010-03-02 18:17:01 -0600363 }
Barry Mienydd671972010-10-04 16:33:58 +0200364
Derek Jonese701d762010-03-02 18:17:01 -0600365 /*
366 * Compact any exploded words
367 *
Derek Jones37f4b9c2011-07-01 17:56:50 -0500368 * This corrects words like: j a v a s c r i p t
Derek Jonese701d762010-03-02 18:17:01 -0600369 * These words are compacted back to their correct state.
Derek Jonese701d762010-03-02 18:17:01 -0600370 */
Pascal Krietec9c045a2011-04-05 14:50:41 -0400371 $words = array(
Wes Bakerd3481352012-05-07 16:49:33 -0400372 'javascript', 'expression', 'vbscript', 'script', 'base64',
Timothy Warren40403d22012-04-19 16:38:50 -0400373 'applet', 'alert', 'document', 'write', 'cookie', 'window'
374 );
David Behler07b53422011-08-15 00:25:06 +0200375
Derek Jones37f4b9c2011-07-01 17:56:50 -0500376
Derek Jonese701d762010-03-02 18:17:01 -0600377 foreach ($words as $word)
378 {
Andrey Andreev67ccdc02012-02-27 23:57:58 +0200379 $word = implode('\s*', str_split($word)).'\s*';
Derek Jonese701d762010-03-02 18:17:01 -0600380
381 // We only want to do this when it is followed by a non-word character
382 // That way valid stuff like "dealer to" does not become "dealerto"
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300383 $str = preg_replace_callback('#('.substr($word, 0, -3).')(\W)#is', array($this, '_compact_exploded_words'), $str);
Derek Jonese701d762010-03-02 18:17:01 -0600384 }
Barry Mienydd671972010-10-04 16:33:58 +0200385
Derek Jonese701d762010-03-02 18:17:01 -0600386 /*
387 * Remove disallowed Javascript in links or img tags
David Behler07b53422011-08-15 00:25:06 +0200388 * We used to do some version comparisons and use of stripos for PHP5,
389 * but it is dog slow compared to these simplified non-capturing
Pascal Krietec9c045a2011-04-05 14:50:41 -0400390 * preg_match(), especially if the pattern exists in the string
Derek Jonese701d762010-03-02 18:17:01 -0600391 */
392 do
393 {
394 $original = $str;
Barry Mienydd671972010-10-04 16:33:58 +0200395
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200396 if (preg_match('/<a/i', $str))
Derek Jonese701d762010-03-02 18:17:01 -0600397 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200398 $str = preg_replace_callback('#<a\s+([^>]*?)(>|$)#si', array($this, '_js_link_removal'), $str);
Derek Jonese701d762010-03-02 18:17:01 -0600399 }
Barry Mienydd671972010-10-04 16:33:58 +0200400
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200401 if (preg_match('/<img/i', $str))
Derek Jonese701d762010-03-02 18:17:01 -0600402 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200403 $str = preg_replace_callback('#<img\s+([^>]*?)(\s?/?>|$)#si', array($this, '_js_img_removal'), $str);
Derek Jonese701d762010-03-02 18:17:01 -0600404 }
Barry Mienydd671972010-10-04 16:33:58 +0200405
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200406 if (preg_match('/(script|xss)/i', $str))
Derek Jonese701d762010-03-02 18:17:01 -0600407 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200408 $str = preg_replace('#<(/*)(script|xss)(.*?)\>#si', '[removed]', $str);
Derek Jonese701d762010-03-02 18:17:01 -0600409 }
410 }
Pascal Krietec9c045a2011-04-05 14:50:41 -0400411 while($original != $str);
Derek Jonese701d762010-03-02 18:17:01 -0600412
413 unset($original);
414
Pascal Krietec9c045a2011-04-05 14:50:41 -0400415 // Remove evil attributes such as style, onclick and xmlns
416 $str = $this->_remove_evil_attributes($str, $is_image);
Barry Mienydd671972010-10-04 16:33:58 +0200417
Derek Jonese701d762010-03-02 18:17:01 -0600418 /*
419 * Sanitize naughty HTML elements
420 *
421 * If a tag containing any of the words in the list
422 * below is found, the tag gets converted to entities.
423 *
424 * So this: <blink>
425 * Becomes: &lt;blink&gt;
Derek Jonese701d762010-03-02 18:17:01 -0600426 */
427 $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';
428 $str = preg_replace_callback('#<(/*\s*)('.$naughty.')([^><]*)([><]*)#is', array($this, '_sanitize_naughty_html'), $str);
429
430 /*
431 * Sanitize naughty scripting elements
432 *
433 * Similar to above, only instead of looking for
434 * tags it looks for PHP and JavaScript commands
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200435 * that are disallowed. Rather than removing the
Derek Jonese701d762010-03-02 18:17:01 -0600436 * code, it simply converts the parenthesis to entities
437 * rendering the code un-executable.
438 *
439 * For example: eval('some code')
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200440 * Becomes: eval&#40;'some code'&#41;
Derek Jonese701d762010-03-02 18:17:01 -0600441 */
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200442 $str = preg_replace('#(alert|cmd|passthru|eval|exec|expression|system|fopen|fsockopen|file|file_get_contents|readfile|unlink)(\s*)\((.*?)\)#si',
443 '\\1\\2&#40;\\3&#41;',
444 $str);
Barry Mienydd671972010-10-04 16:33:58 +0200445
Pascal Krietec9c045a2011-04-05 14:50:41 -0400446 // Final clean up
447 // This adds a bit of extra precaution in case
448 // something got through the above filters
449 $str = $this->_do_never_allowed($str);
Derek Jonese701d762010-03-02 18:17:01 -0600450
451 /*
Pascal Krietec9c045a2011-04-05 14:50:41 -0400452 * Images are Handled in a Special Way
David Behler07b53422011-08-15 00:25:06 +0200453 * - Essentially, we want to know that after all of the character
454 * conversion is done whether any unwanted, likely XSS, code was found.
Pascal Krietec9c045a2011-04-05 14:50:41 -0400455 * If not, we return TRUE, as the image is clean.
David Behler07b53422011-08-15 00:25:06 +0200456 * However, if the string post-conversion does not matched the
457 * string post-removal of XSS, then it fails, as there was unwanted XSS
Pascal Krietec9c045a2011-04-05 14:50:41 -0400458 * code found and removed/changed during processing.
Derek Jonese701d762010-03-02 18:17:01 -0600459 */
Derek Jonese701d762010-03-02 18:17:01 -0600460 if ($is_image === TRUE)
461 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200462 return ($str === $converted_string);
Derek Jonese701d762010-03-02 18:17:01 -0600463 }
Barry Mienydd671972010-10-04 16:33:58 +0200464
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200465 log_message('debug', 'XSS Filtering completed');
Derek Jonese701d762010-03-02 18:17:01 -0600466 return $str;
467 }
468
469 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200470
Derek Jonese701d762010-03-02 18:17:01 -0600471 /**
472 * Random Hash for protecting URLs
473 *
Derek Jonese701d762010-03-02 18:17:01 -0600474 * @return string
475 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500476 public function xss_hash()
Barry Mienydd671972010-10-04 16:33:58 +0200477 {
Pascal Krietec9c045a2011-04-05 14:50:41 -0400478 if ($this->_xss_hash == '')
Derek Jonese701d762010-03-02 18:17:01 -0600479 {
Pascal Krietec38e3b62011-11-14 13:55:00 -0500480 mt_srand();
Pascal Krietec9c045a2011-04-05 14:50:41 -0400481 $this->_xss_hash = md5(time() + mt_rand(0, 1999999999));
Derek Jonese701d762010-03-02 18:17:01 -0600482 }
483
Pascal Krietec9c045a2011-04-05 14:50:41 -0400484 return $this->_xss_hash;
Derek Jonese701d762010-03-02 18:17:01 -0600485 }
486
487 // --------------------------------------------------------------------
488
489 /**
Derek Jonesa0911472010-03-30 10:33:09 -0500490 * HTML Entities Decode
491 *
492 * This function is a replacement for html_entity_decode()
493 *
Pascal Krietec38e3b62011-11-14 13:55:00 -0500494 * The reason we are not using html_entity_decode() by itself is because
495 * while it is not technically correct to leave out the semicolon
496 * at the end of an entity most browsers will still interpret the entity
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200497 * correctly. html_entity_decode() does not convert entities without
Pascal Krietec38e3b62011-11-14 13:55:00 -0500498 * semicolons, so we are left with our own little solution here. Bummer.
Derek Jonesa0911472010-03-30 10:33:09 -0500499 *
Derek Jonesa0911472010-03-30 10:33:09 -0500500 * @param string
501 * @param string
502 * @return string
503 */
freewil8cc0cfe2011-08-27 21:53:00 -0400504 public function entity_decode($str, $charset = NULL)
Derek Jonesa0911472010-03-30 10:33:09 -0500505 {
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300506 if (strpos($str, '&') === FALSE)
freewil5c9b0d12011-08-28 12:15:23 -0400507 {
508 return $str;
509 }
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300510
freewil5c9b0d12011-08-28 12:15:23 -0400511 if (empty($charset))
512 {
513 $charset = config_item('charset');
514 }
Barry Mienydd671972010-10-04 16:33:58 +0200515
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300516 $str = html_entity_decode($str, ENT_COMPAT, $charset);
517 $str = preg_replace('~&#x(0*[0-9a-f]{2,5})~ei', 'chr(hexdec("\\1"))', $str);
518 return preg_replace('~&#([0-9]{2,4})~e', 'chr(\\1)', $str);
Derek Jonesa0911472010-03-30 10:33:09 -0500519 }
Barry Mienydd671972010-10-04 16:33:58 +0200520
Derek Jonesa0911472010-03-30 10:33:09 -0500521 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200522
Derek Jonesa0911472010-03-30 10:33:09 -0500523 /**
Derek Jonese701d762010-03-02 18:17:01 -0600524 * Filename Security
525 *
Derek Jonese701d762010-03-02 18:17:01 -0600526 * @param string
David Behler07b53422011-08-15 00:25:06 +0200527 * @param bool
Derek Jonese701d762010-03-02 18:17:01 -0600528 * @return string
529 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500530 public function sanitize_filename($str, $relative_path = FALSE)
Derek Jonese701d762010-03-02 18:17:01 -0600531 {
532 $bad = array(
Timothy Warren40403d22012-04-19 16:38:50 -0400533 '../', '<!--', '-->', '<', '>',
534 "'", '"', '&', '$', '#',
535 '{', '}', '[', ']', '=',
536 ';', '?', '%20', '%22',
537 '%3c', // <
538 '%253c', // <
539 '%3e', // >
540 '%0e', // >
541 '%28', // (
542 '%29', // )
543 '%2528', // (
544 '%26', // &
545 '%24', // $
546 '%3f', // ?
547 '%3b', // ;
548 '%3d' // =
549 );
David Behler07b53422011-08-15 00:25:06 +0200550
Derek Jones2ef37592010-10-06 17:51:59 -0500551 if ( ! $relative_path)
552 {
553 $bad[] = './';
554 $bad[] = '/';
555 }
Derek Jonese701d762010-03-02 18:17:01 -0600556
Pascal Krietec9c045a2011-04-05 14:50:41 -0400557 $str = remove_invisible_characters($str, FALSE);
Derek Jonese701d762010-03-02 18:17:01 -0600558 return stripslashes(str_replace($bad, '', $str));
559 }
560
Pascal Krietec9c045a2011-04-05 14:50:41 -0400561 // ----------------------------------------------------------------
562
563 /**
564 * Compact Exploded Words
565 *
566 * Callback function for xss_clean() to remove whitespace from
567 * things like j a v a s c r i p t
568 *
Timothy Warrenad475052012-04-19 13:21:06 -0400569 * @param array
570 * @return string
Pascal Krietec9c045a2011-04-05 14:50:41 -0400571 */
572 protected function _compact_exploded_words($matches)
573 {
574 return preg_replace('/\s+/s', '', $matches[1]).$matches[2];
575 }
576
577 // --------------------------------------------------------------------
David Behler07b53422011-08-15 00:25:06 +0200578
Timothy Warrenad475052012-04-19 13:21:06 -0400579 /**
580 * Remove Evil HTML Attributes (like event handlers and style)
Pascal Krietec9c045a2011-04-05 14:50:41 -0400581 *
582 * It removes the evil attribute and either:
583 * - Everything up until a space
584 * For example, everything between the pipes:
585 * <a |style=document.write('hello');alert('world');| class=link>
David Behler07b53422011-08-15 00:25:06 +0200586 * - Everything inside the quotes
Pascal Krietec9c045a2011-04-05 14:50:41 -0400587 * For example, everything between the pipes:
588 * <a |style="document.write('hello'); alert('world');"| class="link">
589 *
590 * @param string $str The string to check
591 * @param boolean $is_image TRUE if this is an image
592 * @return string The string with the evil attributes removed
593 */
594 protected function _remove_evil_attributes($str, $is_image)
595 {
596 // All javascript event handlers (e.g. onload, onclick, onmouseover), style, and xmlns
Pascal Krietec38e3b62011-11-14 13:55:00 -0500597 $evil_attributes = array('on\w*', 'style', 'xmlns', 'formaction');
Pascal Krietec9c045a2011-04-05 14:50:41 -0400598
599 if ($is_image === TRUE)
600 {
601 /*
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200602 * Adobe Photoshop puts XML metadata into JFIF images,
Pascal Krietec9c045a2011-04-05 14:50:41 -0400603 * including namespacing, so we have to allow this for images.
604 */
605 unset($evil_attributes[array_search('xmlns', $evil_attributes)]);
606 }
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200607
Pascal Krietec9c045a2011-04-05 14:50:41 -0400608 do {
Pascal Krietec38e3b62011-11-14 13:55:00 -0500609 $count = 0;
610 $attribs = array();
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200611
Pascal Krietec38e3b62011-11-14 13:55:00 -0500612 // find occurrences of illegal attribute strings without quotes
Wes Baker5335bc32012-04-24 15:17:14 -0400613 preg_match_all('/('.implode('|', $evil_attributes).')\s*=\s*([^\s>]*)/is', $str, $matches, PREG_SET_ORDER);
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200614
Pascal Krietec38e3b62011-11-14 13:55:00 -0500615 foreach ($matches as $attr)
616 {
Wes Baker5335bc32012-04-24 15:17:14 -0400617
Pascal Krietec38e3b62011-11-14 13:55:00 -0500618 $attribs[] = preg_quote($attr[0], '/');
619 }
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200620
Pascal Krietec38e3b62011-11-14 13:55:00 -0500621 // find occurrences of illegal attribute strings with quotes (042 and 047 are octal quotes)
Andrey Andreev67ccdc02012-02-27 23:57:58 +0200622 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 +0200623
Pascal Krietec38e3b62011-11-14 13:55:00 -0500624 foreach ($matches as $attr)
625 {
626 $attribs[] = preg_quote($attr[0], '/');
627 }
628
629 // replace illegal attribute strings that are inside an html tag
630 if (count($attribs) > 0)
631 {
Andrey Andreev92ebfb62012-05-17 12:49:24 +0300632 $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 -0500633 }
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200634
Pascal Krietec38e3b62011-11-14 13:55:00 -0500635 } while ($count);
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200636
Pascal Krietec9c045a2011-04-05 14:50:41 -0400637 return $str;
638 }
David Behler07b53422011-08-15 00:25:06 +0200639
Pascal Krietec9c045a2011-04-05 14:50:41 -0400640 // --------------------------------------------------------------------
641
642 /**
643 * Sanitize Naughty HTML
644 *
645 * Callback function for xss_clean() to remove naughty HTML elements
646 *
647 * @param array
648 * @return string
649 */
650 protected function _sanitize_naughty_html($matches)
651 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200652 return '&lt;'.$matches[1].$matches[2].$matches[3] // encode opening brace
653 // encode captured opening or closing brace to prevent recursive vectors:
Andrey Andreev67ccdc02012-02-27 23:57:58 +0200654 .str_replace(array('>', '<'), array('&gt;', '&lt;'), $matches[4]);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400655 }
656
657 // --------------------------------------------------------------------
658
659 /**
660 * JS Link Removal
661 *
662 * Callback function for xss_clean() to sanitize links
663 * This limits the PCRE backtracks, making it more performance friendly
664 * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in
665 * PHP 5.2+ on link-heavy strings
666 *
667 * @param array
668 * @return string
669 */
670 protected function _js_link_removal($match)
671 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200672 return str_replace($match[1],
Wes Baker5335bc32012-04-24 15:17:14 -0400673 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 +0200674 '',
675 $this->_filter_attributes(str_replace(array('<', '>'), '', $match[1]))
676 ),
677 $match[0]);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400678 }
679
680 // --------------------------------------------------------------------
681
682 /**
683 * JS Image Removal
684 *
685 * Callback function for xss_clean() to sanitize image tags
686 * This limits the PCRE backtracks, making it more performance friendly
687 * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in
688 * PHP 5.2+ on image tag heavy strings
689 *
690 * @param array
691 * @return string
692 */
693 protected function _js_img_removal($match)
694 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200695 return str_replace($match[1],
696 preg_replace('#src=.*?(alert\(|alert&\#40;|javascript\:|livescript\:|mocha\:|charset\=|window\.|document\.|\.cookie|<script|<xss|base64\s*,)#si',
697 '',
698 $this->_filter_attributes(str_replace(array('<', '>'), '', $match[1]))
699 ),
700 $match[0]);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400701 }
702
703 // --------------------------------------------------------------------
704
705 /**
706 * Attribute Conversion
707 *
708 * Used as a callback for XSS Clean
709 *
710 * @param array
711 * @return string
712 */
713 protected function _convert_attribute($match)
714 {
715 return str_replace(array('>', '<', '\\'), array('&gt;', '&lt;', '\\\\'), $match[0]);
716 }
717
718 // --------------------------------------------------------------------
719
720 /**
721 * Filter Attributes
722 *
723 * Filters tag attributes for consistency and safety
724 *
725 * @param string
726 * @return string
727 */
728 protected function _filter_attributes($str)
729 {
730 $out = '';
Pascal Krietec9c045a2011-04-05 14:50:41 -0400731 if (preg_match_all('#\s*[a-z\-]+\s*=\s*(\042|\047)([^\\1]*?)\\1#is', $str, $matches))
732 {
733 foreach ($matches[0] as $match)
734 {
Andrey Andreev4562f2c2012-01-09 23:39:50 +0200735 $out .= preg_replace('#/\*.*?\*/#s', '', $match);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400736 }
737 }
738
739 return $out;
740 }
741
742 // --------------------------------------------------------------------
743
744 /**
745 * HTML Entity Decode Callback
746 *
747 * Used as a callback for XSS Clean
748 *
749 * @param array
750 * @return string
751 */
752 protected function _decode_entity($match)
753 {
754 return $this->entity_decode($match[0], strtoupper(config_item('charset')));
755 }
756
757 // --------------------------------------------------------------------
David Behler07b53422011-08-15 00:25:06 +0200758
Pascal Krietec9c045a2011-04-05 14:50:41 -0400759 /**
760 * Validate URL entities
761 *
762 * Called by xss_clean()
763 *
David Behler07b53422011-08-15 00:25:06 +0200764 * @param string
Pascal Krietec9c045a2011-04-05 14:50:41 -0400765 * @return string
766 */
767 protected function _validate_entities($str)
768 {
769 /*
770 * Protect GET variables in URLs
771 */
David Behler07b53422011-08-15 00:25:06 +0200772
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200773 // 901119URL5918AMP18930PROTECT8198
774 $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 -0400775
776 /*
777 * Validate standard character entities
778 *
Derek Jones37f4b9c2011-07-01 17:56:50 -0500779 * Add a semicolon if missing. We do this to enable
Pascal Krietec9c045a2011-04-05 14:50:41 -0400780 * the conversion of entities to ASCII later.
Pascal Krietec9c045a2011-04-05 14:50:41 -0400781 */
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200782 $str = preg_replace('#(&\#?[0-9a-z]{2,})([\x00-\x20])*;?#i', '\\1;\\2', $str);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400783
784 /*
785 * Validate UTF16 two byte encoding (x00)
786 *
787 * Just as above, adds a semicolon if missing.
Pascal Krietec9c045a2011-04-05 14:50:41 -0400788 */
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200789 $str = preg_replace('#(&\#x?)([0-9A-F]+);?#i', '\\1\\2;', $str);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400790
791 /*
792 * Un-Protect GET variables in URLs
793 */
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200794 return str_replace($this->xss_hash(), '&', $str);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400795 }
796
797 // ----------------------------------------------------------------------
798
799 /**
800 * Do Never Allowed
801 *
802 * A utility function for xss_clean()
803 *
804 * @param string
805 * @return string
806 */
807 protected function _do_never_allowed($str)
808 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200809 $str = str_replace(array_keys($this->_never_allowed_str), $this->_never_allowed_str, $str);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400810
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200811 foreach ($this->_never_allowed_regex as $regex)
Pascal Krietec9c045a2011-04-05 14:50:41 -0400812 {
Wes Baker5335bc32012-04-24 15:17:14 -0400813 $str = preg_replace('#'.$regex.'#is', '[removed]', $str);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400814 }
David Behler07b53422011-08-15 00:25:06 +0200815
Pascal Krietec9c045a2011-04-05 14:50:41 -0400816 return $str;
817 }
818
819 // --------------------------------------------------------------------
820
821 /**
822 * Set Cross Site Request Forgery Protection Cookie
823 *
824 * @return string
825 */
826 protected function _csrf_set_hash()
827 {
828 if ($this->_csrf_hash == '')
829 {
David Behler07b53422011-08-15 00:25:06 +0200830 // If the cookie exists we will use it's value.
Pascal Krietec9c045a2011-04-05 14:50:41 -0400831 // We don't necessarily want to regenerate it with
David Behler07b53422011-08-15 00:25:06 +0200832 // each page load since a page could contain embedded
Pascal Krietec9c045a2011-04-05 14:50:41 -0400833 // sub-pages causing this feature to fail
David Behler07b53422011-08-15 00:25:06 +0200834 if (isset($_COOKIE[$this->_csrf_cookie_name]) &&
Alexander Hofstedee2c374f2012-05-17 00:28:08 +0200835 preg_match('#^[0-9a-f]{32}$#iS', $_COOKIE[$this->_csrf_cookie_name]) === 1)
Pascal Krietec9c045a2011-04-05 14:50:41 -0400836 {
837 return $this->_csrf_hash = $_COOKIE[$this->_csrf_cookie_name];
838 }
David Behler07b53422011-08-15 00:25:06 +0200839
Chris Berthed93e6f32011-09-25 10:33:25 -0400840 $this->_csrf_hash = md5(uniqid(rand(), TRUE));
841 $this->csrf_set_cookie();
Pascal Krietec9c045a2011-04-05 14:50:41 -0400842 }
843
844 return $this->_csrf_hash;
845 }
846
Derek Jonese701d762010-03-02 18:17:01 -0600847}
Derek Jonese701d762010-03-02 18:17:01 -0600848
849/* End of file Security.php */
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200850/* Location: ./system/core/Security.php */