blob: 65746637b7b81ab514e2ee638ade3a59268b783d [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 */
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!
Wes Baker5335bc32012-04-24 15:17:14 -0400102 'Redirect\s+302',
103 "([\"'])?data\s*:[^\\1]*?base64[^\\1]*?,[^\\1]*?\\1?"
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200104 );
David Behler07b53422011-08-15 00:25:06 +0200105
Greg Akera9263282010-11-10 15:26:43 -0600106 public function __construct()
Derek Jonese701d762010-03-02 18:17:01 -0600107 {
Andrey Andreev67ccdc02012-02-27 23:57:58 +0200108 // Is CSRF protection enabled?
109 if (config_item('csrf_protection') === TRUE)
patworkef1a55a2011-04-09 13:04:06 +0200110 {
Andrey Andreev67ccdc02012-02-27 23:57:58 +0200111 // CSRF config
112 foreach (array('csrf_expire', 'csrf_token_name', 'csrf_cookie_name') as $key)
patworkef1a55a2011-04-09 13:04:06 +0200113 {
Andrey Andreev67ccdc02012-02-27 23:57:58 +0200114 if (FALSE !== ($val = config_item($key)))
115 {
116 $this->{'_'.$key} = $val;
117 }
patworkef1a55a2011-04-09 13:04:06 +0200118 }
patworkef1a55a2011-04-09 13:04:06 +0200119
Andrey Andreev67ccdc02012-02-27 23:57:58 +0200120 // Append application specific cookie prefix
121 if (config_item('cookie_prefix'))
122 {
123 $this->_csrf_cookie_name = config_item('cookie_prefix').$this->_csrf_cookie_name;
124 }
Derek Jonesb3f10a22010-07-25 19:11:26 -0500125
Andrey Andreev67ccdc02012-02-27 23:57:58 +0200126 // Set the CSRF hash
127 $this->_csrf_set_hash();
128 }
Derek Allard958543a2010-07-22 14:10:26 -0400129
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200130 log_message('debug', 'Security Class Initialized');
Derek Jonese701d762010-03-02 18:17:01 -0600131 }
132
133 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200134
Derek Jonese701d762010-03-02 18:17:01 -0600135 /**
136 * Verify Cross Site Request Forgery Protection
137 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400138 * @return object
Derek Jonese701d762010-03-02 18:17:01 -0600139 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500140 public function csrf_verify()
Derek Allard958543a2010-07-22 14:10:26 -0400141 {
Andrey Andreev5d27c432012-03-08 12:01:52 +0200142 // If it's not a POST request we will set the CSRF cookie
143 if (strtoupper($_SERVER['REQUEST_METHOD']) !== 'POST')
Derek Jonese701d762010-03-02 18:17:01 -0600144 {
145 return $this->csrf_set_cookie();
146 }
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300147
Alex Bilbieaeb2c3e2011-08-21 16:14:54 +0100148 // Check if URI has been whitelisted from CSRF checks
149 if ($exclude_uris = config_item('csrf_exclude_uris'))
150 {
151 $uri = load_class('URI', 'core');
152 if (in_array($uri->uri_string(), $exclude_uris))
153 {
154 return $this;
155 }
156 }
Derek Jonese701d762010-03-02 18:17:01 -0600157
158 // Do the tokens exist in both the _POST and _COOKIE arrays?
Andrey Andreev4562f2c2012-01-09 23:39:50 +0200159 if ( ! isset($_POST[$this->_csrf_token_name]) OR ! isset($_COOKIE[$this->_csrf_cookie_name])
160 OR $_POST[$this->_csrf_token_name] != $_COOKIE[$this->_csrf_cookie_name]) // Do the tokens match?
Derek Jonese701d762010-03-02 18:17:01 -0600161 {
162 $this->csrf_show_error();
163 }
164
Andrey Andreev4562f2c2012-01-09 23:39:50 +0200165 // We kill this since we're done and we don't want to polute the _POST array
Pascal Krietec9c045a2011-04-05 14:50:41 -0400166 unset($_POST[$this->_csrf_token_name]);
Barry Mienydd671972010-10-04 16:33:58 +0200167
RS712be25a62011-12-31 16:02:04 -0200168 // Regenerate on every submission?
169 if (config_item('csrf_regenerate'))
170 {
171 // Nothing should last forever
172 unset($_COOKIE[$this->_csrf_cookie_name]);
173 $this->_csrf_hash = '';
174 }
Andrey Andreev8a7d0782012-01-08 05:43:42 +0200175
Derek Jonesb3f10a22010-07-25 19:11:26 -0500176 $this->_csrf_set_hash();
177 $this->csrf_set_cookie();
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300178
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200179 log_message('debug', 'CSRF token verified');
Pascal Krietec9c045a2011-04-05 14:50:41 -0400180 return $this;
Derek Jonese701d762010-03-02 18:17:01 -0600181 }
Barry Mienydd671972010-10-04 16:33:58 +0200182
Derek Jonese701d762010-03-02 18:17:01 -0600183 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200184
Derek Jonese701d762010-03-02 18:17:01 -0600185 /**
186 * Set Cross Site Request Forgery Protection Cookie
187 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400188 * @return object
Derek Jonese701d762010-03-02 18:17:01 -0600189 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500190 public function csrf_set_cookie()
Derek Jonese701d762010-03-02 18:17:01 -0600191 {
Pascal Krietec9c045a2011-04-05 14:50:41 -0400192 $expire = time() + $this->_csrf_expire;
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300193 $secure_cookie = (bool) config_item('cookie_secure');
Derek Jonese701d762010-03-02 18:17:01 -0600194
Andrey Andreeva10c8e12012-02-29 18:56:12 +0200195 if ($secure_cookie && (empty($_SERVER['HTTPS']) OR strtolower($_SERVER['HTTPS']) === 'off'))
Derek Jonese701d762010-03-02 18:17:01 -0600196 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200197 return FALSE;
Derek Jonese701d762010-03-02 18:17:01 -0600198 }
Derek Allard958543a2010-07-22 14:10:26 -0400199
freewil4ad0fd82012-03-13 22:37:42 -0400200 setcookie(
201 $this->_csrf_cookie_name,
202 $this->_csrf_hash,
203 $expire,
204 config_item('cookie_path'),
205 config_item('cookie_domain'),
206 $secure_cookie,
207 config_item('cookie_httponly')
208 );
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200209 log_message('debug', 'CRSF cookie Set');
David Behler07b53422011-08-15 00:25:06 +0200210
Pascal Krietec9c045a2011-04-05 14:50:41 -0400211 return $this;
Derek Jonese701d762010-03-02 18:17:01 -0600212 }
213
214 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200215
Derek Jonese701d762010-03-02 18:17:01 -0600216 /**
217 * Show CSRF Error
218 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400219 * @return void
Derek Jonese701d762010-03-02 18:17:01 -0600220 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500221 public function csrf_show_error()
Derek Jonese701d762010-03-02 18:17:01 -0600222 {
223 show_error('The action you have requested is not allowed.');
224 }
225
226 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200227
Derek Jonese701d762010-03-02 18:17:01 -0600228 /**
David Behler07b53422011-08-15 00:25:06 +0200229 * Get CSRF Hash
Pascal Krietec9c045a2011-04-05 14:50:41 -0400230 *
David Behler07b53422011-08-15 00:25:06 +0200231 * Getter Method
Pascal Krietec9c045a2011-04-05 14:50:41 -0400232 *
233 * @return string self::_csrf_hash
234 */
235 public function get_csrf_hash()
236 {
237 return $this->_csrf_hash;
238 }
239
240 // --------------------------------------------------------------------
241
242 /**
243 * Get CSRF Token Name
244 *
245 * Getter Method
246 *
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200247 * @return string self::_csrf_token_name
Pascal Krietec9c045a2011-04-05 14:50:41 -0400248 */
249 public function get_csrf_token_name()
250 {
251 return $this->_csrf_token_name;
252 }
253
254 // --------------------------------------------------------------------
255
256 /**
Derek Jonese701d762010-03-02 18:17:01 -0600257 * XSS Clean
258 *
259 * Sanitizes data so that Cross Site Scripting Hacks can be
Derek Jones37f4b9c2011-07-01 17:56:50 -0500260 * prevented. This function does a fair amount of work but
Derek Jonese701d762010-03-02 18:17:01 -0600261 * it is extremely thorough, designed to prevent even the
Derek Jones37f4b9c2011-07-01 17:56:50 -0500262 * most obscure XSS attempts. Nothing is ever 100% foolproof,
Derek Jonese701d762010-03-02 18:17:01 -0600263 * of course, but I haven't been able to get anything passed
264 * the filter.
265 *
266 * Note: This function should only be used to deal with data
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200267 * upon submission. It's not something that should
Derek Jonese701d762010-03-02 18:17:01 -0600268 * be used for general runtime processing.
269 *
270 * This function was based in part on some code and ideas I
271 * got from Bitflux: http://channel.bitflux.ch/wiki/XSS_Prevention
272 *
273 * To help develop this script I used this great list of
274 * vulnerabilities along with a few other hacks I've
275 * harvested from examining vulnerabilities in other programs:
276 * http://ha.ckers.org/xss.html
277 *
Derek Jonese701d762010-03-02 18:17:01 -0600278 * @param mixed string or array
David Behler07b53422011-08-15 00:25:06 +0200279 * @param bool
Derek Jonese701d762010-03-02 18:17:01 -0600280 * @return string
281 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500282 public function xss_clean($str, $is_image = FALSE)
Derek Jonese701d762010-03-02 18:17:01 -0600283 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200284 // Is the string an array?
Derek Jonese701d762010-03-02 18:17:01 -0600285 if (is_array($str))
286 {
287 while (list($key) = each($str))
288 {
289 $str[$key] = $this->xss_clean($str[$key]);
290 }
Barry Mienydd671972010-10-04 16:33:58 +0200291
Derek Jonese701d762010-03-02 18:17:01 -0600292 return $str;
293 }
294
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200295 // Remove Invisible Characters and validate entities in URLs
296 $str = $this->_validate_entities(remove_invisible_characters($str));
Derek Jonese701d762010-03-02 18:17:01 -0600297
298 /*
299 * URL Decode
300 *
301 * Just in case stuff like this is submitted:
302 *
303 * <a href="http://%77%77%77%2E%67%6F%6F%67%6C%65%2E%63%6F%6D">Google</a>
304 *
305 * Note: Use rawurldecode() so it does not remove plus signs
Derek Jonese701d762010-03-02 18:17:01 -0600306 */
307 $str = rawurldecode($str);
Barry Mienydd671972010-10-04 16:33:58 +0200308
Derek Jonese701d762010-03-02 18:17:01 -0600309 /*
Barry Mienydd671972010-10-04 16:33:58 +0200310 * Convert character entities to ASCII
Derek Jonese701d762010-03-02 18:17:01 -0600311 *
312 * This permits our tests below to work reliably.
313 * We only convert entities that are within tags since
314 * these are the ones that will pose security problems.
Derek Jonese701d762010-03-02 18:17:01 -0600315 */
Derek Jonese701d762010-03-02 18:17:01 -0600316 $str = preg_replace_callback("/[a-z]+=([\'\"]).*?\\1/si", array($this, '_convert_attribute'), $str);
Andrey Andreev4562f2c2012-01-09 23:39:50 +0200317 $str = preg_replace_callback('/<\w+.*?(?=>|<|$)/si', array($this, '_decode_entity'), $str);
Derek Jonese701d762010-03-02 18:17:01 -0600318
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200319 // Remove Invisible Characters Again!
Greg Aker757dda62010-04-14 19:06:19 -0500320 $str = remove_invisible_characters($str);
Barry Mienydd671972010-10-04 16:33:58 +0200321
Derek Jonese701d762010-03-02 18:17:01 -0600322 /*
323 * Convert all tabs to spaces
324 *
325 * This prevents strings like this: ja vascript
326 * NOTE: we deal with spaces between characters later.
David Behler07b53422011-08-15 00:25:06 +0200327 * NOTE: preg_replace was found to be amazingly slow here on
Pascal Krietec9c045a2011-04-05 14:50:41 -0400328 * large blocks of data, so we use str_replace.
Derek Jonese701d762010-03-02 18:17:01 -0600329 */
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200330 $str = str_replace("\t", ' ', $str);
Barry Mienydd671972010-10-04 16:33:58 +0200331
Andrey Andreev4562f2c2012-01-09 23:39:50 +0200332 // Capture converted string for later comparison
Derek Jonese701d762010-03-02 18:17:01 -0600333 $converted_string = $str;
Barry Mienydd671972010-10-04 16:33:58 +0200334
Pascal Krietec9c045a2011-04-05 14:50:41 -0400335 // Remove Strings that are never allowed
336 $str = $this->_do_never_allowed($str);
Derek Jonese701d762010-03-02 18:17:01 -0600337
338 /*
339 * Makes PHP tags safe
340 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400341 * Note: XML tags are inadvertently replaced too:
Derek Jonese701d762010-03-02 18:17:01 -0600342 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400343 * <?xml
Derek Jonese701d762010-03-02 18:17:01 -0600344 *
345 * But it doesn't seem to pose a problem.
Derek Jonese701d762010-03-02 18:17:01 -0600346 */
347 if ($is_image === TRUE)
348 {
David Behler07b53422011-08-15 00:25:06 +0200349 // Images have a tendency to have the PHP short opening and
350 // closing tags every so often so we skip those and only
Pascal Krietec9c045a2011-04-05 14:50:41 -0400351 // do the long opening tags.
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200352 $str = preg_replace('/<\?(php)/i', '&lt;?\\1', $str);
Derek Jonese701d762010-03-02 18:17:01 -0600353 }
354 else
355 {
Derek Jones37f4b9c2011-07-01 17:56:50 -0500356 $str = str_replace(array('<?', '?'.'>'), array('&lt;?', '?&gt;'), $str);
Derek Jonese701d762010-03-02 18:17:01 -0600357 }
Barry Mienydd671972010-10-04 16:33:58 +0200358
Derek Jonese701d762010-03-02 18:17:01 -0600359 /*
360 * Compact any exploded words
361 *
Derek Jones37f4b9c2011-07-01 17:56:50 -0500362 * This corrects words like: j a v a s c r i p t
Derek Jonese701d762010-03-02 18:17:01 -0600363 * These words are compacted back to their correct state.
Derek Jonese701d762010-03-02 18:17:01 -0600364 */
Pascal Krietec9c045a2011-04-05 14:50:41 -0400365 $words = array(
Wes Baker5335bc32012-04-24 15:17:14 -0400366 'javascript', 'expression', 'vbscript', 'script', 'base64',
Pascal Krietec9c045a2011-04-05 14:50:41 -0400367 'applet', 'alert', 'document', 'write', 'cookie', 'window'
368 );
David Behler07b53422011-08-15 00:25:06 +0200369
Derek Jonese701d762010-03-02 18:17:01 -0600370 foreach ($words as $word)
371 {
Andrey Andreev67ccdc02012-02-27 23:57:58 +0200372 $word = implode('\s*', str_split($word)).'\s*';
Derek Jonese701d762010-03-02 18:17:01 -0600373
374 // We only want to do this when it is followed by a non-word character
375 // That way valid stuff like "dealer to" does not become "dealerto"
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300376 $str = preg_replace_callback('#('.substr($word, 0, -3).')(\W)#is', array($this, '_compact_exploded_words'), $str);
Derek Jonese701d762010-03-02 18:17:01 -0600377 }
Barry Mienydd671972010-10-04 16:33:58 +0200378
Derek Jonese701d762010-03-02 18:17:01 -0600379 /*
380 * Remove disallowed Javascript in links or img tags
David Behler07b53422011-08-15 00:25:06 +0200381 * We used to do some version comparisons and use of stripos for PHP5,
382 * but it is dog slow compared to these simplified non-capturing
Pascal Krietec9c045a2011-04-05 14:50:41 -0400383 * preg_match(), especially if the pattern exists in the string
Derek Jonese701d762010-03-02 18:17:01 -0600384 */
385 do
386 {
387 $original = $str;
Barry Mienydd671972010-10-04 16:33:58 +0200388
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200389 if (preg_match('/<a/i', $str))
Derek Jonese701d762010-03-02 18:17:01 -0600390 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200391 $str = preg_replace_callback('#<a\s+([^>]*?)(>|$)#si', array($this, '_js_link_removal'), $str);
Derek Jonese701d762010-03-02 18:17:01 -0600392 }
Barry Mienydd671972010-10-04 16:33:58 +0200393
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200394 if (preg_match('/<img/i', $str))
Derek Jonese701d762010-03-02 18:17:01 -0600395 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200396 $str = preg_replace_callback('#<img\s+([^>]*?)(\s?/?>|$)#si', array($this, '_js_img_removal'), $str);
Derek Jonese701d762010-03-02 18:17:01 -0600397 }
Barry Mienydd671972010-10-04 16:33:58 +0200398
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200399 if (preg_match('/(script|xss)/i', $str))
Derek Jonese701d762010-03-02 18:17:01 -0600400 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200401 $str = preg_replace('#<(/*)(script|xss)(.*?)\>#si', '[removed]', $str);
Derek Jonese701d762010-03-02 18:17:01 -0600402 }
403 }
Pascal Krietec9c045a2011-04-05 14:50:41 -0400404 while($original != $str);
Derek Jonese701d762010-03-02 18:17:01 -0600405
406 unset($original);
407
Pascal Krietec9c045a2011-04-05 14:50:41 -0400408 // Remove evil attributes such as style, onclick and xmlns
409 $str = $this->_remove_evil_attributes($str, $is_image);
Barry Mienydd671972010-10-04 16:33:58 +0200410
Derek Jonese701d762010-03-02 18:17:01 -0600411 /*
412 * Sanitize naughty HTML elements
413 *
414 * If a tag containing any of the words in the list
415 * below is found, the tag gets converted to entities.
416 *
417 * So this: <blink>
418 * Becomes: &lt;blink&gt;
Derek Jonese701d762010-03-02 18:17:01 -0600419 */
420 $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';
421 $str = preg_replace_callback('#<(/*\s*)('.$naughty.')([^><]*)([><]*)#is', array($this, '_sanitize_naughty_html'), $str);
422
423 /*
424 * Sanitize naughty scripting elements
425 *
426 * Similar to above, only instead of looking for
427 * tags it looks for PHP and JavaScript commands
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200428 * that are disallowed. Rather than removing the
Derek Jonese701d762010-03-02 18:17:01 -0600429 * code, it simply converts the parenthesis to entities
430 * rendering the code un-executable.
431 *
432 * For example: eval('some code')
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200433 * Becomes: eval&#40;'some code'&#41;
Derek Jonese701d762010-03-02 18:17:01 -0600434 */
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200435 $str = preg_replace('#(alert|cmd|passthru|eval|exec|expression|system|fopen|fsockopen|file|file_get_contents|readfile|unlink)(\s*)\((.*?)\)#si',
436 '\\1\\2&#40;\\3&#41;',
437 $str);
Barry Mienydd671972010-10-04 16:33:58 +0200438
Pascal Krietec9c045a2011-04-05 14:50:41 -0400439 // Final clean up
440 // This adds a bit of extra precaution in case
441 // something got through the above filters
442 $str = $this->_do_never_allowed($str);
Derek Jonese701d762010-03-02 18:17:01 -0600443
444 /*
Pascal Krietec9c045a2011-04-05 14:50:41 -0400445 * Images are Handled in a Special Way
David Behler07b53422011-08-15 00:25:06 +0200446 * - Essentially, we want to know that after all of the character
447 * conversion is done whether any unwanted, likely XSS, code was found.
Pascal Krietec9c045a2011-04-05 14:50:41 -0400448 * If not, we return TRUE, as the image is clean.
David Behler07b53422011-08-15 00:25:06 +0200449 * However, if the string post-conversion does not matched the
450 * string post-removal of XSS, then it fails, as there was unwanted XSS
Pascal Krietec9c045a2011-04-05 14:50:41 -0400451 * code found and removed/changed during processing.
Derek Jonese701d762010-03-02 18:17:01 -0600452 */
Derek Jonese701d762010-03-02 18:17:01 -0600453 if ($is_image === TRUE)
454 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200455 return ($str === $converted_string);
Derek Jonese701d762010-03-02 18:17:01 -0600456 }
Barry Mienydd671972010-10-04 16:33:58 +0200457
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200458 log_message('debug', 'XSS Filtering completed');
Derek Jonese701d762010-03-02 18:17:01 -0600459 return $str;
460 }
461
462 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200463
Derek Jonese701d762010-03-02 18:17:01 -0600464 /**
465 * Random Hash for protecting URLs
466 *
Derek Jonese701d762010-03-02 18:17:01 -0600467 * @return string
468 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500469 public function xss_hash()
Barry Mienydd671972010-10-04 16:33:58 +0200470 {
Pascal Krietec9c045a2011-04-05 14:50:41 -0400471 if ($this->_xss_hash == '')
Derek Jonese701d762010-03-02 18:17:01 -0600472 {
Pascal Krietec38e3b62011-11-14 13:55:00 -0500473 mt_srand();
Pascal Krietec9c045a2011-04-05 14:50:41 -0400474 $this->_xss_hash = md5(time() + mt_rand(0, 1999999999));
Derek Jonese701d762010-03-02 18:17:01 -0600475 }
476
Pascal Krietec9c045a2011-04-05 14:50:41 -0400477 return $this->_xss_hash;
Derek Jonese701d762010-03-02 18:17:01 -0600478 }
479
480 // --------------------------------------------------------------------
481
482 /**
Derek Jonesa0911472010-03-30 10:33:09 -0500483 * HTML Entities Decode
484 *
485 * This function is a replacement for html_entity_decode()
486 *
Pascal Krietec38e3b62011-11-14 13:55:00 -0500487 * The reason we are not using html_entity_decode() by itself is because
488 * while it is not technically correct to leave out the semicolon
489 * at the end of an entity most browsers will still interpret the entity
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200490 * correctly. html_entity_decode() does not convert entities without
Pascal Krietec38e3b62011-11-14 13:55:00 -0500491 * semicolons, so we are left with our own little solution here. Bummer.
Derek Jonesa0911472010-03-30 10:33:09 -0500492 *
Derek Jonesa0911472010-03-30 10:33:09 -0500493 * @param string
494 * @param string
495 * @return string
496 */
freewil8cc0cfe2011-08-27 21:53:00 -0400497 public function entity_decode($str, $charset = NULL)
Derek Jonesa0911472010-03-30 10:33:09 -0500498 {
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300499 if (strpos($str, '&') === FALSE)
freewil5c9b0d12011-08-28 12:15:23 -0400500 {
501 return $str;
502 }
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300503
freewil5c9b0d12011-08-28 12:15:23 -0400504 if (empty($charset))
505 {
506 $charset = config_item('charset');
507 }
Barry Mienydd671972010-10-04 16:33:58 +0200508
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300509 $str = html_entity_decode($str, ENT_COMPAT, $charset);
510 $str = preg_replace('~&#x(0*[0-9a-f]{2,5})~ei', 'chr(hexdec("\\1"))', $str);
511 return preg_replace('~&#([0-9]{2,4})~e', 'chr(\\1)', $str);
Derek Jonesa0911472010-03-30 10:33:09 -0500512 }
Barry Mienydd671972010-10-04 16:33:58 +0200513
Derek Jonesa0911472010-03-30 10:33:09 -0500514 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200515
Derek Jonesa0911472010-03-30 10:33:09 -0500516 /**
Derek Jonese701d762010-03-02 18:17:01 -0600517 * Filename Security
518 *
Derek Jonese701d762010-03-02 18:17:01 -0600519 * @param string
David Behler07b53422011-08-15 00:25:06 +0200520 * @param bool
Derek Jonese701d762010-03-02 18:17:01 -0600521 * @return string
522 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500523 public function sanitize_filename($str, $relative_path = FALSE)
Derek Jonese701d762010-03-02 18:17:01 -0600524 {
525 $bad = array(
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200526 '../', '<!--', '-->', '<', '>',
527 "'", '"', '&', '$', '#',
528 '{', '}', '[', ']', '=',
529 ';', '?', '%20', '%22',
530 '%3c', // <
531 '%253c', // <
532 '%3e', // >
533 '%0e', // >
534 '%28', // (
535 '%29', // )
536 '%2528', // (
537 '%26', // &
538 '%24', // $
539 '%3f', // ?
540 '%3b', // ;
541 '%3d' // =
542 );
David Behler07b53422011-08-15 00:25:06 +0200543
Derek Jones2ef37592010-10-06 17:51:59 -0500544 if ( ! $relative_path)
545 {
546 $bad[] = './';
547 $bad[] = '/';
548 }
Derek Jonese701d762010-03-02 18:17:01 -0600549
Pascal Krietec9c045a2011-04-05 14:50:41 -0400550 $str = remove_invisible_characters($str, FALSE);
Derek Jonese701d762010-03-02 18:17:01 -0600551 return stripslashes(str_replace($bad, '', $str));
552 }
553
Pascal Krietec9c045a2011-04-05 14:50:41 -0400554 // ----------------------------------------------------------------
555
556 /**
557 * Compact Exploded Words
558 *
559 * Callback function for xss_clean() to remove whitespace from
560 * things like j a v a s c r i p t
561 *
562 * @param type
563 * @return type
564 */
565 protected function _compact_exploded_words($matches)
566 {
567 return preg_replace('/\s+/s', '', $matches[1]).$matches[2];
568 }
569
570 // --------------------------------------------------------------------
David Behler07b53422011-08-15 00:25:06 +0200571
Pascal Krietec9c045a2011-04-05 14:50:41 -0400572 /*
573 * Remove Evil HTML Attributes (like evenhandlers and style)
574 *
575 * It removes the evil attribute and either:
576 * - Everything up until a space
577 * For example, everything between the pipes:
578 * <a |style=document.write('hello');alert('world');| class=link>
David Behler07b53422011-08-15 00:25:06 +0200579 * - Everything inside the quotes
Pascal Krietec9c045a2011-04-05 14:50:41 -0400580 * For example, everything between the pipes:
581 * <a |style="document.write('hello'); alert('world');"| class="link">
582 *
583 * @param string $str The string to check
584 * @param boolean $is_image TRUE if this is an image
585 * @return string The string with the evil attributes removed
586 */
587 protected function _remove_evil_attributes($str, $is_image)
588 {
589 // All javascript event handlers (e.g. onload, onclick, onmouseover), style, and xmlns
Pascal Krietec38e3b62011-11-14 13:55:00 -0500590 $evil_attributes = array('on\w*', 'style', 'xmlns', 'formaction');
Pascal Krietec9c045a2011-04-05 14:50:41 -0400591
592 if ($is_image === TRUE)
593 {
594 /*
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200595 * Adobe Photoshop puts XML metadata into JFIF images,
Pascal Krietec9c045a2011-04-05 14:50:41 -0400596 * including namespacing, so we have to allow this for images.
597 */
598 unset($evil_attributes[array_search('xmlns', $evil_attributes)]);
599 }
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200600
Pascal Krietec9c045a2011-04-05 14:50:41 -0400601 do {
Pascal Krietec38e3b62011-11-14 13:55:00 -0500602 $count = 0;
603 $attribs = array();
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200604
Pascal Krietec38e3b62011-11-14 13:55:00 -0500605 // find occurrences of illegal attribute strings without quotes
Wes Baker5335bc32012-04-24 15:17:14 -0400606 preg_match_all('/('.implode('|', $evil_attributes).')\s*=\s*([^\s>]*)/is', $str, $matches, PREG_SET_ORDER);
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200607
Pascal Krietec38e3b62011-11-14 13:55:00 -0500608 foreach ($matches as $attr)
609 {
Wes Baker5335bc32012-04-24 15:17:14 -0400610
Pascal Krietec38e3b62011-11-14 13:55:00 -0500611 $attribs[] = preg_quote($attr[0], '/');
612 }
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200613
Pascal Krietec38e3b62011-11-14 13:55:00 -0500614 // find occurrences of illegal attribute strings with quotes (042 and 047 are octal quotes)
Andrey Andreev67ccdc02012-02-27 23:57:58 +0200615 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 +0200616
Pascal Krietec38e3b62011-11-14 13:55:00 -0500617 foreach ($matches as $attr)
618 {
619 $attribs[] = preg_quote($attr[0], '/');
620 }
621
622 // replace illegal attribute strings that are inside an html tag
623 if (count($attribs) > 0)
624 {
Wes Baker5335bc32012-04-24 15:17:14 -0400625 $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 -0500626 }
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200627
Pascal Krietec38e3b62011-11-14 13:55:00 -0500628 } while ($count);
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200629
Pascal Krietec9c045a2011-04-05 14:50:41 -0400630 return $str;
631 }
David Behler07b53422011-08-15 00:25:06 +0200632
Pascal Krietec9c045a2011-04-05 14:50:41 -0400633 // --------------------------------------------------------------------
634
635 /**
636 * Sanitize Naughty HTML
637 *
638 * Callback function for xss_clean() to remove naughty HTML elements
639 *
640 * @param array
641 * @return string
642 */
643 protected function _sanitize_naughty_html($matches)
644 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200645 return '&lt;'.$matches[1].$matches[2].$matches[3] // encode opening brace
646 // encode captured opening or closing brace to prevent recursive vectors:
Andrey Andreev67ccdc02012-02-27 23:57:58 +0200647 .str_replace(array('>', '<'), array('&gt;', '&lt;'), $matches[4]);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400648 }
649
650 // --------------------------------------------------------------------
651
652 /**
653 * JS Link Removal
654 *
655 * Callback function for xss_clean() to sanitize links
656 * This limits the PCRE backtracks, making it more performance friendly
657 * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in
658 * PHP 5.2+ on link-heavy strings
659 *
660 * @param array
661 * @return string
662 */
663 protected function _js_link_removal($match)
664 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200665 return str_replace($match[1],
Wes Baker5335bc32012-04-24 15:17:14 -0400666 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 +0200667 '',
668 $this->_filter_attributes(str_replace(array('<', '>'), '', $match[1]))
669 ),
670 $match[0]);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400671 }
672
673 // --------------------------------------------------------------------
674
675 /**
676 * JS Image Removal
677 *
678 * Callback function for xss_clean() to sanitize image tags
679 * This limits the PCRE backtracks, making it more performance friendly
680 * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in
681 * PHP 5.2+ on image tag heavy strings
682 *
683 * @param array
684 * @return string
685 */
686 protected function _js_img_removal($match)
687 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200688 return str_replace($match[1],
689 preg_replace('#src=.*?(alert\(|alert&\#40;|javascript\:|livescript\:|mocha\:|charset\=|window\.|document\.|\.cookie|<script|<xss|base64\s*,)#si',
690 '',
691 $this->_filter_attributes(str_replace(array('<', '>'), '', $match[1]))
692 ),
693 $match[0]);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400694 }
695
696 // --------------------------------------------------------------------
697
698 /**
699 * Attribute Conversion
700 *
701 * Used as a callback for XSS Clean
702 *
703 * @param array
704 * @return string
705 */
706 protected function _convert_attribute($match)
707 {
708 return str_replace(array('>', '<', '\\'), array('&gt;', '&lt;', '\\\\'), $match[0]);
709 }
710
711 // --------------------------------------------------------------------
712
713 /**
714 * Filter Attributes
715 *
716 * Filters tag attributes for consistency and safety
717 *
718 * @param string
719 * @return string
720 */
721 protected function _filter_attributes($str)
722 {
723 $out = '';
Pascal Krietec9c045a2011-04-05 14:50:41 -0400724 if (preg_match_all('#\s*[a-z\-]+\s*=\s*(\042|\047)([^\\1]*?)\\1#is', $str, $matches))
725 {
726 foreach ($matches[0] as $match)
727 {
Andrey Andreev4562f2c2012-01-09 23:39:50 +0200728 $out .= preg_replace('#/\*.*?\*/#s', '', $match);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400729 }
730 }
731
732 return $out;
733 }
734
735 // --------------------------------------------------------------------
736
737 /**
738 * HTML Entity Decode Callback
739 *
740 * Used as a callback for XSS Clean
741 *
742 * @param array
743 * @return string
744 */
745 protected function _decode_entity($match)
746 {
747 return $this->entity_decode($match[0], strtoupper(config_item('charset')));
748 }
749
750 // --------------------------------------------------------------------
David Behler07b53422011-08-15 00:25:06 +0200751
Pascal Krietec9c045a2011-04-05 14:50:41 -0400752 /**
753 * Validate URL entities
754 *
755 * Called by xss_clean()
756 *
David Behler07b53422011-08-15 00:25:06 +0200757 * @param string
Pascal Krietec9c045a2011-04-05 14:50:41 -0400758 * @return string
759 */
760 protected function _validate_entities($str)
761 {
762 /*
763 * Protect GET variables in URLs
764 */
David Behler07b53422011-08-15 00:25:06 +0200765
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200766 // 901119URL5918AMP18930PROTECT8198
767 $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 -0400768
769 /*
770 * Validate standard character entities
771 *
Derek Jones37f4b9c2011-07-01 17:56:50 -0500772 * Add a semicolon if missing. We do this to enable
Pascal Krietec9c045a2011-04-05 14:50:41 -0400773 * the conversion of entities to ASCII later.
Pascal Krietec9c045a2011-04-05 14:50:41 -0400774 */
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200775 $str = preg_replace('#(&\#?[0-9a-z]{2,})([\x00-\x20])*;?#i', '\\1;\\2', $str);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400776
777 /*
778 * Validate UTF16 two byte encoding (x00)
779 *
780 * Just as above, adds a semicolon if missing.
Pascal Krietec9c045a2011-04-05 14:50:41 -0400781 */
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200782 $str = preg_replace('#(&\#x?)([0-9A-F]+);?#i', '\\1\\2;', $str);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400783
784 /*
785 * Un-Protect GET variables in URLs
786 */
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200787 return str_replace($this->xss_hash(), '&', $str);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400788 }
789
790 // ----------------------------------------------------------------------
791
792 /**
793 * Do Never Allowed
794 *
795 * A utility function for xss_clean()
796 *
797 * @param string
798 * @return string
799 */
800 protected function _do_never_allowed($str)
801 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200802 $str = str_replace(array_keys($this->_never_allowed_str), $this->_never_allowed_str, $str);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400803
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200804 foreach ($this->_never_allowed_regex as $regex)
Pascal Krietec9c045a2011-04-05 14:50:41 -0400805 {
Wes Baker5335bc32012-04-24 15:17:14 -0400806 $str = preg_replace('#'.$regex.'#is', '[removed]', $str);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400807 }
David Behler07b53422011-08-15 00:25:06 +0200808
Pascal Krietec9c045a2011-04-05 14:50:41 -0400809 return $str;
810 }
811
812 // --------------------------------------------------------------------
813
814 /**
815 * Set Cross Site Request Forgery Protection Cookie
816 *
817 * @return string
818 */
819 protected function _csrf_set_hash()
820 {
821 if ($this->_csrf_hash == '')
822 {
David Behler07b53422011-08-15 00:25:06 +0200823 // If the cookie exists we will use it's value.
Pascal Krietec9c045a2011-04-05 14:50:41 -0400824 // We don't necessarily want to regenerate it with
David Behler07b53422011-08-15 00:25:06 +0200825 // each page load since a page could contain embedded
Pascal Krietec9c045a2011-04-05 14:50:41 -0400826 // sub-pages causing this feature to fail
David Behler07b53422011-08-15 00:25:06 +0200827 if (isset($_COOKIE[$this->_csrf_cookie_name]) &&
Pascal Krietec9c045a2011-04-05 14:50:41 -0400828 $_COOKIE[$this->_csrf_cookie_name] != '')
829 {
830 return $this->_csrf_hash = $_COOKIE[$this->_csrf_cookie_name];
831 }
David Behler07b53422011-08-15 00:25:06 +0200832
Chris Berthed93e6f32011-09-25 10:33:25 -0400833 $this->_csrf_hash = md5(uniqid(rand(), TRUE));
834 $this->csrf_set_cookie();
Pascal Krietec9c045a2011-04-05 14:50:41 -0400835 }
836
837 return $this->_csrf_hash;
838 }
839
Derek Jonese701d762010-03-02 18:17:01 -0600840}
Derek Jonese701d762010-03-02 18:17:01 -0600841
842/* End of file Security.php */
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200843/* Location: ./system/core/Security.php */