blob: 81b6602ae32ccf356ffde3b907d802c592245076 [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
Derek Jonese701d762010-03-02 18:17:01 -0600194 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500195 public function csrf_set_cookie()
Derek Jonese701d762010-03-02 18:17:01 -0600196 {
Pascal Krietec9c045a2011-04-05 14:50:41 -0400197 $expire = time() + $this->_csrf_expire;
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300198 $secure_cookie = (bool) config_item('cookie_secure');
Derek Jonese701d762010-03-02 18:17:01 -0600199
Andrey Andreeva10c8e12012-02-29 18:56:12 +0200200 if ($secure_cookie && (empty($_SERVER['HTTPS']) OR strtolower($_SERVER['HTTPS']) === 'off'))
Derek Jonese701d762010-03-02 18:17:01 -0600201 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200202 return FALSE;
Derek Jonese701d762010-03-02 18:17:01 -0600203 }
Derek Allard958543a2010-07-22 14:10:26 -0400204
freewil4ad0fd82012-03-13 22:37:42 -0400205 setcookie(
Andrey Andreev92ebfb62012-05-17 12:49:24 +0300206 $this->_csrf_cookie_name,
207 $this->_csrf_hash,
208 $expire,
209 config_item('cookie_path'),
210 config_item('cookie_domain'),
freewil4ad0fd82012-03-13 22:37:42 -0400211 $secure_cookie,
212 config_item('cookie_httponly')
213 );
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200214 log_message('debug', 'CRSF cookie Set');
David Behler07b53422011-08-15 00:25:06 +0200215
Pascal Krietec9c045a2011-04-05 14:50:41 -0400216 return $this;
Derek Jonese701d762010-03-02 18:17:01 -0600217 }
218
219 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200220
Derek Jonese701d762010-03-02 18:17:01 -0600221 /**
222 * Show CSRF Error
223 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400224 * @return void
Derek Jonese701d762010-03-02 18:17:01 -0600225 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500226 public function csrf_show_error()
Derek Jonese701d762010-03-02 18:17:01 -0600227 {
228 show_error('The action you have requested is not allowed.');
229 }
230
231 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200232
Derek Jonese701d762010-03-02 18:17:01 -0600233 /**
David Behler07b53422011-08-15 00:25:06 +0200234 * Get CSRF Hash
Pascal Krietec9c045a2011-04-05 14:50:41 -0400235 *
David Behler07b53422011-08-15 00:25:06 +0200236 * Getter Method
Pascal Krietec9c045a2011-04-05 14:50:41 -0400237 *
238 * @return string self::_csrf_hash
239 */
240 public function get_csrf_hash()
241 {
242 return $this->_csrf_hash;
243 }
244
245 // --------------------------------------------------------------------
246
247 /**
248 * Get CSRF Token Name
249 *
250 * Getter Method
251 *
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200252 * @return string self::_csrf_token_name
Pascal Krietec9c045a2011-04-05 14:50:41 -0400253 */
254 public function get_csrf_token_name()
255 {
256 return $this->_csrf_token_name;
257 }
258
259 // --------------------------------------------------------------------
260
261 /**
Derek Jonese701d762010-03-02 18:17:01 -0600262 * XSS Clean
263 *
264 * Sanitizes data so that Cross Site Scripting Hacks can be
Derek Jones37f4b9c2011-07-01 17:56:50 -0500265 * prevented. This function does a fair amount of work but
Derek Jonese701d762010-03-02 18:17:01 -0600266 * it is extremely thorough, designed to prevent even the
Derek Jones37f4b9c2011-07-01 17:56:50 -0500267 * most obscure XSS attempts. Nothing is ever 100% foolproof,
Derek Jonese701d762010-03-02 18:17:01 -0600268 * of course, but I haven't been able to get anything passed
269 * the filter.
270 *
271 * Note: This function should only be used to deal with data
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200272 * upon submission. It's not something that should
Derek Jonese701d762010-03-02 18:17:01 -0600273 * be used for general runtime processing.
274 *
275 * This function was based in part on some code and ideas I
276 * got from Bitflux: http://channel.bitflux.ch/wiki/XSS_Prevention
277 *
278 * To help develop this script I used this great list of
279 * vulnerabilities along with a few other hacks I've
280 * harvested from examining vulnerabilities in other programs:
281 * http://ha.ckers.org/xss.html
282 *
Derek Jonese701d762010-03-02 18:17:01 -0600283 * @param mixed string or array
David Behler07b53422011-08-15 00:25:06 +0200284 * @param bool
Derek Jonese701d762010-03-02 18:17:01 -0600285 * @return string
286 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500287 public function xss_clean($str, $is_image = FALSE)
Derek Jonese701d762010-03-02 18:17:01 -0600288 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200289 // Is the string an array?
Derek Jonese701d762010-03-02 18:17:01 -0600290 if (is_array($str))
291 {
292 while (list($key) = each($str))
293 {
294 $str[$key] = $this->xss_clean($str[$key]);
295 }
Barry Mienydd671972010-10-04 16:33:58 +0200296
Derek Jonese701d762010-03-02 18:17:01 -0600297 return $str;
298 }
299
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200300 // Remove Invisible Characters and validate entities in URLs
301 $str = $this->_validate_entities(remove_invisible_characters($str));
Derek Jonese701d762010-03-02 18:17:01 -0600302
303 /*
304 * URL Decode
305 *
306 * Just in case stuff like this is submitted:
307 *
308 * <a href="http://%77%77%77%2E%67%6F%6F%67%6C%65%2E%63%6F%6D">Google</a>
309 *
310 * Note: Use rawurldecode() so it does not remove plus signs
Derek Jonese701d762010-03-02 18:17:01 -0600311 */
312 $str = rawurldecode($str);
Barry Mienydd671972010-10-04 16:33:58 +0200313
Derek Jonese701d762010-03-02 18:17:01 -0600314 /*
Barry Mienydd671972010-10-04 16:33:58 +0200315 * Convert character entities to ASCII
Derek Jonese701d762010-03-02 18:17:01 -0600316 *
317 * This permits our tests below to work reliably.
318 * We only convert entities that are within tags since
319 * these are the ones that will pose security problems.
Derek Jonese701d762010-03-02 18:17:01 -0600320 */
Derek Jonese701d762010-03-02 18:17:01 -0600321 $str = preg_replace_callback("/[a-z]+=([\'\"]).*?\\1/si", array($this, '_convert_attribute'), $str);
Andrey Andreev4562f2c2012-01-09 23:39:50 +0200322 $str = preg_replace_callback('/<\w+.*?(?=>|<|$)/si', array($this, '_decode_entity'), $str);
Derek Jonese701d762010-03-02 18:17:01 -0600323
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200324 // Remove Invisible Characters Again!
Greg Aker757dda62010-04-14 19:06:19 -0500325 $str = remove_invisible_characters($str);
Barry Mienydd671972010-10-04 16:33:58 +0200326
Derek Jonese701d762010-03-02 18:17:01 -0600327 /*
328 * Convert all tabs to spaces
329 *
330 * This prevents strings like this: ja vascript
331 * NOTE: we deal with spaces between characters later.
David Behler07b53422011-08-15 00:25:06 +0200332 * NOTE: preg_replace was found to be amazingly slow here on
Pascal Krietec9c045a2011-04-05 14:50:41 -0400333 * large blocks of data, so we use str_replace.
Derek Jonese701d762010-03-02 18:17:01 -0600334 */
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200335 $str = str_replace("\t", ' ', $str);
Barry Mienydd671972010-10-04 16:33:58 +0200336
Andrey Andreev4562f2c2012-01-09 23:39:50 +0200337 // Capture converted string for later comparison
Derek Jonese701d762010-03-02 18:17:01 -0600338 $converted_string = $str;
Barry Mienydd671972010-10-04 16:33:58 +0200339
Pascal Krietec9c045a2011-04-05 14:50:41 -0400340 // Remove Strings that are never allowed
341 $str = $this->_do_never_allowed($str);
Derek Jonese701d762010-03-02 18:17:01 -0600342
343 /*
344 * Makes PHP tags safe
345 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400346 * Note: XML tags are inadvertently replaced too:
Derek Jonese701d762010-03-02 18:17:01 -0600347 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400348 * <?xml
Derek Jonese701d762010-03-02 18:17:01 -0600349 *
350 * But it doesn't seem to pose a problem.
Derek Jonese701d762010-03-02 18:17:01 -0600351 */
352 if ($is_image === TRUE)
353 {
David Behler07b53422011-08-15 00:25:06 +0200354 // Images have a tendency to have the PHP short opening and
355 // closing tags every so often so we skip those and only
Pascal Krietec9c045a2011-04-05 14:50:41 -0400356 // do the long opening tags.
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200357 $str = preg_replace('/<\?(php)/i', '&lt;?\\1', $str);
Derek Jonese701d762010-03-02 18:17:01 -0600358 }
359 else
360 {
Derek Jones37f4b9c2011-07-01 17:56:50 -0500361 $str = str_replace(array('<?', '?'.'>'), array('&lt;?', '?&gt;'), $str);
Derek Jonese701d762010-03-02 18:17:01 -0600362 }
Barry Mienydd671972010-10-04 16:33:58 +0200363
Derek Jonese701d762010-03-02 18:17:01 -0600364 /*
365 * Compact any exploded words
366 *
Derek Jones37f4b9c2011-07-01 17:56:50 -0500367 * This corrects words like: j a v a s c r i p t
Derek Jonese701d762010-03-02 18:17:01 -0600368 * These words are compacted back to their correct state.
Derek Jonese701d762010-03-02 18:17:01 -0600369 */
Pascal Krietec9c045a2011-04-05 14:50:41 -0400370 $words = array(
Wes Bakerd3481352012-05-07 16:49:33 -0400371 'javascript', 'expression', 'vbscript', 'script', 'base64',
Timothy Warren40403d22012-04-19 16:38:50 -0400372 'applet', 'alert', 'document', 'write', 'cookie', 'window'
373 );
David Behler07b53422011-08-15 00:25:06 +0200374
Derek Jones37f4b9c2011-07-01 17:56:50 -0500375
Derek Jonese701d762010-03-02 18:17:01 -0600376 foreach ($words as $word)
377 {
Andrey Andreev67ccdc02012-02-27 23:57:58 +0200378 $word = implode('\s*', str_split($word)).'\s*';
Derek Jonese701d762010-03-02 18:17:01 -0600379
380 // We only want to do this when it is followed by a non-word character
381 // That way valid stuff like "dealer to" does not become "dealerto"
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300382 $str = preg_replace_callback('#('.substr($word, 0, -3).')(\W)#is', array($this, '_compact_exploded_words'), $str);
Derek Jonese701d762010-03-02 18:17:01 -0600383 }
Barry Mienydd671972010-10-04 16:33:58 +0200384
Derek Jonese701d762010-03-02 18:17:01 -0600385 /*
386 * Remove disallowed Javascript in links or img tags
David Behler07b53422011-08-15 00:25:06 +0200387 * We used to do some version comparisons and use of stripos for PHP5,
388 * but it is dog slow compared to these simplified non-capturing
Pascal Krietec9c045a2011-04-05 14:50:41 -0400389 * preg_match(), especially if the pattern exists in the string
Derek Jonese701d762010-03-02 18:17:01 -0600390 */
391 do
392 {
393 $original = $str;
Barry Mienydd671972010-10-04 16:33:58 +0200394
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200395 if (preg_match('/<a/i', $str))
Derek Jonese701d762010-03-02 18:17:01 -0600396 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200397 $str = preg_replace_callback('#<a\s+([^>]*?)(>|$)#si', array($this, '_js_link_removal'), $str);
Derek Jonese701d762010-03-02 18:17:01 -0600398 }
Barry Mienydd671972010-10-04 16:33:58 +0200399
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200400 if (preg_match('/<img/i', $str))
Derek Jonese701d762010-03-02 18:17:01 -0600401 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200402 $str = preg_replace_callback('#<img\s+([^>]*?)(\s?/?>|$)#si', array($this, '_js_img_removal'), $str);
Derek Jonese701d762010-03-02 18:17:01 -0600403 }
Barry Mienydd671972010-10-04 16:33:58 +0200404
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200405 if (preg_match('/(script|xss)/i', $str))
Derek Jonese701d762010-03-02 18:17:01 -0600406 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200407 $str = preg_replace('#<(/*)(script|xss)(.*?)\>#si', '[removed]', $str);
Derek Jonese701d762010-03-02 18:17:01 -0600408 }
409 }
Pascal Krietec9c045a2011-04-05 14:50:41 -0400410 while($original != $str);
Derek Jonese701d762010-03-02 18:17:01 -0600411
412 unset($original);
413
Pascal Krietec9c045a2011-04-05 14:50:41 -0400414 // Remove evil attributes such as style, onclick and xmlns
415 $str = $this->_remove_evil_attributes($str, $is_image);
Barry Mienydd671972010-10-04 16:33:58 +0200416
Derek Jonese701d762010-03-02 18:17:01 -0600417 /*
418 * Sanitize naughty HTML elements
419 *
420 * If a tag containing any of the words in the list
421 * below is found, the tag gets converted to entities.
422 *
423 * So this: <blink>
424 * Becomes: &lt;blink&gt;
Derek Jonese701d762010-03-02 18:17:01 -0600425 */
426 $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';
427 $str = preg_replace_callback('#<(/*\s*)('.$naughty.')([^><]*)([><]*)#is', array($this, '_sanitize_naughty_html'), $str);
428
429 /*
430 * Sanitize naughty scripting elements
431 *
432 * Similar to above, only instead of looking for
433 * tags it looks for PHP and JavaScript commands
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200434 * that are disallowed. Rather than removing the
Derek Jonese701d762010-03-02 18:17:01 -0600435 * code, it simply converts the parenthesis to entities
436 * rendering the code un-executable.
437 *
438 * For example: eval('some code')
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200439 * Becomes: eval&#40;'some code'&#41;
Derek Jonese701d762010-03-02 18:17:01 -0600440 */
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200441 $str = preg_replace('#(alert|cmd|passthru|eval|exec|expression|system|fopen|fsockopen|file|file_get_contents|readfile|unlink)(\s*)\((.*?)\)#si',
442 '\\1\\2&#40;\\3&#41;',
443 $str);
Barry Mienydd671972010-10-04 16:33:58 +0200444
Pascal Krietec9c045a2011-04-05 14:50:41 -0400445 // Final clean up
446 // This adds a bit of extra precaution in case
447 // something got through the above filters
448 $str = $this->_do_never_allowed($str);
Derek Jonese701d762010-03-02 18:17:01 -0600449
450 /*
Pascal Krietec9c045a2011-04-05 14:50:41 -0400451 * Images are Handled in a Special Way
David Behler07b53422011-08-15 00:25:06 +0200452 * - Essentially, we want to know that after all of the character
453 * conversion is done whether any unwanted, likely XSS, code was found.
Pascal Krietec9c045a2011-04-05 14:50:41 -0400454 * If not, we return TRUE, as the image is clean.
David Behler07b53422011-08-15 00:25:06 +0200455 * However, if the string post-conversion does not matched the
456 * string post-removal of XSS, then it fails, as there was unwanted XSS
Pascal Krietec9c045a2011-04-05 14:50:41 -0400457 * code found and removed/changed during processing.
Derek Jonese701d762010-03-02 18:17:01 -0600458 */
Derek Jonese701d762010-03-02 18:17:01 -0600459 if ($is_image === TRUE)
460 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200461 return ($str === $converted_string);
Derek Jonese701d762010-03-02 18:17:01 -0600462 }
Barry Mienydd671972010-10-04 16:33:58 +0200463
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200464 log_message('debug', 'XSS Filtering completed');
Derek Jonese701d762010-03-02 18:17:01 -0600465 return $str;
466 }
467
468 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200469
Derek Jonese701d762010-03-02 18:17:01 -0600470 /**
471 * Random Hash for protecting URLs
472 *
Derek Jonese701d762010-03-02 18:17:01 -0600473 * @return string
474 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500475 public function xss_hash()
Barry Mienydd671972010-10-04 16:33:58 +0200476 {
Pascal Krietec9c045a2011-04-05 14:50:41 -0400477 if ($this->_xss_hash == '')
Derek Jonese701d762010-03-02 18:17:01 -0600478 {
Pascal Krietec38e3b62011-11-14 13:55:00 -0500479 mt_srand();
Pascal Krietec9c045a2011-04-05 14:50:41 -0400480 $this->_xss_hash = md5(time() + mt_rand(0, 1999999999));
Derek Jonese701d762010-03-02 18:17:01 -0600481 }
482
Pascal Krietec9c045a2011-04-05 14:50:41 -0400483 return $this->_xss_hash;
Derek Jonese701d762010-03-02 18:17:01 -0600484 }
485
486 // --------------------------------------------------------------------
487
488 /**
Derek Jonesa0911472010-03-30 10:33:09 -0500489 * HTML Entities Decode
490 *
491 * This function is a replacement for html_entity_decode()
492 *
Pascal Krietec38e3b62011-11-14 13:55:00 -0500493 * The reason we are not using html_entity_decode() by itself is because
494 * while it is not technically correct to leave out the semicolon
495 * at the end of an entity most browsers will still interpret the entity
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200496 * correctly. html_entity_decode() does not convert entities without
Pascal Krietec38e3b62011-11-14 13:55:00 -0500497 * semicolons, so we are left with our own little solution here. Bummer.
Derek Jonesa0911472010-03-30 10:33:09 -0500498 *
Derek Jonesa0911472010-03-30 10:33:09 -0500499 * @param string
500 * @param string
501 * @return string
502 */
freewil8cc0cfe2011-08-27 21:53:00 -0400503 public function entity_decode($str, $charset = NULL)
Derek Jonesa0911472010-03-30 10:33:09 -0500504 {
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300505 if (strpos($str, '&') === FALSE)
freewil5c9b0d12011-08-28 12:15:23 -0400506 {
507 return $str;
508 }
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300509
freewil5c9b0d12011-08-28 12:15:23 -0400510 if (empty($charset))
511 {
512 $charset = config_item('charset');
513 }
Barry Mienydd671972010-10-04 16:33:58 +0200514
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300515 $str = html_entity_decode($str, ENT_COMPAT, $charset);
516 $str = preg_replace('~&#x(0*[0-9a-f]{2,5})~ei', 'chr(hexdec("\\1"))', $str);
517 return preg_replace('~&#([0-9]{2,4})~e', 'chr(\\1)', $str);
Derek Jonesa0911472010-03-30 10:33:09 -0500518 }
Barry Mienydd671972010-10-04 16:33:58 +0200519
Derek Jonesa0911472010-03-30 10:33:09 -0500520 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200521
Derek Jonesa0911472010-03-30 10:33:09 -0500522 /**
Derek Jonese701d762010-03-02 18:17:01 -0600523 * Filename Security
524 *
Derek Jonese701d762010-03-02 18:17:01 -0600525 * @param string
David Behler07b53422011-08-15 00:25:06 +0200526 * @param bool
Derek Jonese701d762010-03-02 18:17:01 -0600527 * @return string
528 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500529 public function sanitize_filename($str, $relative_path = FALSE)
Derek Jonese701d762010-03-02 18:17:01 -0600530 {
531 $bad = array(
Timothy Warren40403d22012-04-19 16:38:50 -0400532 '../', '<!--', '-->', '<', '>',
533 "'", '"', '&', '$', '#',
534 '{', '}', '[', ']', '=',
535 ';', '?', '%20', '%22',
536 '%3c', // <
537 '%253c', // <
538 '%3e', // >
539 '%0e', // >
540 '%28', // (
541 '%29', // )
542 '%2528', // (
543 '%26', // &
544 '%24', // $
545 '%3f', // ?
546 '%3b', // ;
547 '%3d' // =
548 );
David Behler07b53422011-08-15 00:25:06 +0200549
Derek Jones2ef37592010-10-06 17:51:59 -0500550 if ( ! $relative_path)
551 {
552 $bad[] = './';
553 $bad[] = '/';
554 }
Derek Jonese701d762010-03-02 18:17:01 -0600555
Pascal Krietec9c045a2011-04-05 14:50:41 -0400556 $str = remove_invisible_characters($str, FALSE);
Derek Jonese701d762010-03-02 18:17:01 -0600557 return stripslashes(str_replace($bad, '', $str));
558 }
559
Pascal Krietec9c045a2011-04-05 14:50:41 -0400560 // ----------------------------------------------------------------
561
562 /**
563 * Compact Exploded Words
564 *
565 * Callback function for xss_clean() to remove whitespace from
566 * things like j a v a s c r i p t
567 *
Timothy Warrenad475052012-04-19 13:21:06 -0400568 * @param array
569 * @return string
Pascal Krietec9c045a2011-04-05 14:50:41 -0400570 */
571 protected function _compact_exploded_words($matches)
572 {
573 return preg_replace('/\s+/s', '', $matches[1]).$matches[2];
574 }
575
576 // --------------------------------------------------------------------
David Behler07b53422011-08-15 00:25:06 +0200577
Timothy Warrenad475052012-04-19 13:21:06 -0400578 /**
579 * Remove Evil HTML Attributes (like event handlers and style)
Pascal Krietec9c045a2011-04-05 14:50:41 -0400580 *
581 * It removes the evil attribute and either:
582 * - Everything up until a space
583 * For example, everything between the pipes:
584 * <a |style=document.write('hello');alert('world');| class=link>
David Behler07b53422011-08-15 00:25:06 +0200585 * - Everything inside the quotes
Pascal Krietec9c045a2011-04-05 14:50:41 -0400586 * For example, everything between the pipes:
587 * <a |style="document.write('hello'); alert('world');"| class="link">
588 *
589 * @param string $str The string to check
590 * @param boolean $is_image TRUE if this is an image
591 * @return string The string with the evil attributes removed
592 */
593 protected function _remove_evil_attributes($str, $is_image)
594 {
595 // All javascript event handlers (e.g. onload, onclick, onmouseover), style, and xmlns
Pascal Krietec38e3b62011-11-14 13:55:00 -0500596 $evil_attributes = array('on\w*', 'style', 'xmlns', 'formaction');
Pascal Krietec9c045a2011-04-05 14:50:41 -0400597
598 if ($is_image === TRUE)
599 {
600 /*
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200601 * Adobe Photoshop puts XML metadata into JFIF images,
Pascal Krietec9c045a2011-04-05 14:50:41 -0400602 * including namespacing, so we have to allow this for images.
603 */
604 unset($evil_attributes[array_search('xmlns', $evil_attributes)]);
605 }
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200606
Pascal Krietec9c045a2011-04-05 14:50:41 -0400607 do {
Pascal Krietec38e3b62011-11-14 13:55:00 -0500608 $count = 0;
609 $attribs = array();
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200610
Pascal Krietec38e3b62011-11-14 13:55:00 -0500611 // find occurrences of illegal attribute strings without quotes
Wes Baker5335bc32012-04-24 15:17:14 -0400612 preg_match_all('/('.implode('|', $evil_attributes).')\s*=\s*([^\s>]*)/is', $str, $matches, PREG_SET_ORDER);
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200613
Pascal Krietec38e3b62011-11-14 13:55:00 -0500614 foreach ($matches as $attr)
615 {
Wes Baker5335bc32012-04-24 15:17:14 -0400616
Pascal Krietec38e3b62011-11-14 13:55:00 -0500617 $attribs[] = preg_quote($attr[0], '/');
618 }
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200619
Pascal Krietec38e3b62011-11-14 13:55:00 -0500620 // find occurrences of illegal attribute strings with quotes (042 and 047 are octal quotes)
Andrey Andreev67ccdc02012-02-27 23:57:58 +0200621 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 +0200622
Pascal Krietec38e3b62011-11-14 13:55:00 -0500623 foreach ($matches as $attr)
624 {
625 $attribs[] = preg_quote($attr[0], '/');
626 }
627
628 // replace illegal attribute strings that are inside an html tag
629 if (count($attribs) > 0)
630 {
Andrey Andreev92ebfb62012-05-17 12:49:24 +0300631 $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 -0500632 }
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200633
Pascal Krietec38e3b62011-11-14 13:55:00 -0500634 } while ($count);
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200635
Pascal Krietec9c045a2011-04-05 14:50:41 -0400636 return $str;
637 }
David Behler07b53422011-08-15 00:25:06 +0200638
Pascal Krietec9c045a2011-04-05 14:50:41 -0400639 // --------------------------------------------------------------------
640
641 /**
642 * Sanitize Naughty HTML
643 *
644 * Callback function for xss_clean() to remove naughty HTML elements
645 *
646 * @param array
647 * @return string
648 */
649 protected function _sanitize_naughty_html($matches)
650 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200651 return '&lt;'.$matches[1].$matches[2].$matches[3] // encode opening brace
652 // encode captured opening or closing brace to prevent recursive vectors:
Andrey Andreev67ccdc02012-02-27 23:57:58 +0200653 .str_replace(array('>', '<'), array('&gt;', '&lt;'), $matches[4]);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400654 }
655
656 // --------------------------------------------------------------------
657
658 /**
659 * JS Link Removal
660 *
661 * Callback function for xss_clean() to sanitize links
662 * This limits the PCRE backtracks, making it more performance friendly
663 * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in
664 * PHP 5.2+ on link-heavy strings
665 *
666 * @param array
667 * @return string
668 */
669 protected function _js_link_removal($match)
670 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200671 return str_replace($match[1],
Wes Baker5335bc32012-04-24 15:17:14 -0400672 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 +0200673 '',
674 $this->_filter_attributes(str_replace(array('<', '>'), '', $match[1]))
675 ),
676 $match[0]);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400677 }
678
679 // --------------------------------------------------------------------
680
681 /**
682 * JS Image Removal
683 *
684 * Callback function for xss_clean() to sanitize image tags
685 * This limits the PCRE backtracks, making it more performance friendly
686 * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in
687 * PHP 5.2+ on image tag heavy strings
688 *
689 * @param array
690 * @return string
691 */
692 protected function _js_img_removal($match)
693 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200694 return str_replace($match[1],
695 preg_replace('#src=.*?(alert\(|alert&\#40;|javascript\:|livescript\:|mocha\:|charset\=|window\.|document\.|\.cookie|<script|<xss|base64\s*,)#si',
696 '',
697 $this->_filter_attributes(str_replace(array('<', '>'), '', $match[1]))
698 ),
699 $match[0]);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400700 }
701
702 // --------------------------------------------------------------------
703
704 /**
705 * Attribute Conversion
706 *
707 * Used as a callback for XSS Clean
708 *
709 * @param array
710 * @return string
711 */
712 protected function _convert_attribute($match)
713 {
714 return str_replace(array('>', '<', '\\'), array('&gt;', '&lt;', '\\\\'), $match[0]);
715 }
716
717 // --------------------------------------------------------------------
718
719 /**
720 * Filter Attributes
721 *
722 * Filters tag attributes for consistency and safety
723 *
724 * @param string
725 * @return string
726 */
727 protected function _filter_attributes($str)
728 {
729 $out = '';
Pascal Krietec9c045a2011-04-05 14:50:41 -0400730 if (preg_match_all('#\s*[a-z\-]+\s*=\s*(\042|\047)([^\\1]*?)\\1#is', $str, $matches))
731 {
732 foreach ($matches[0] as $match)
733 {
Andrey Andreev4562f2c2012-01-09 23:39:50 +0200734 $out .= preg_replace('#/\*.*?\*/#s', '', $match);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400735 }
736 }
737
738 return $out;
739 }
740
741 // --------------------------------------------------------------------
742
743 /**
744 * HTML Entity Decode Callback
745 *
746 * Used as a callback for XSS Clean
747 *
748 * @param array
749 * @return string
750 */
751 protected function _decode_entity($match)
752 {
753 return $this->entity_decode($match[0], strtoupper(config_item('charset')));
754 }
755
756 // --------------------------------------------------------------------
David Behler07b53422011-08-15 00:25:06 +0200757
Pascal Krietec9c045a2011-04-05 14:50:41 -0400758 /**
759 * Validate URL entities
760 *
761 * Called by xss_clean()
762 *
David Behler07b53422011-08-15 00:25:06 +0200763 * @param string
Pascal Krietec9c045a2011-04-05 14:50:41 -0400764 * @return string
765 */
766 protected function _validate_entities($str)
767 {
768 /*
769 * Protect GET variables in URLs
770 */
David Behler07b53422011-08-15 00:25:06 +0200771
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200772 // 901119URL5918AMP18930PROTECT8198
773 $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 -0400774
775 /*
776 * Validate standard character entities
777 *
Derek Jones37f4b9c2011-07-01 17:56:50 -0500778 * Add a semicolon if missing. We do this to enable
Pascal Krietec9c045a2011-04-05 14:50:41 -0400779 * the conversion of entities to ASCII later.
Pascal Krietec9c045a2011-04-05 14:50:41 -0400780 */
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200781 $str = preg_replace('#(&\#?[0-9a-z]{2,})([\x00-\x20])*;?#i', '\\1;\\2', $str);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400782
783 /*
784 * Validate UTF16 two byte encoding (x00)
785 *
786 * Just as above, adds a semicolon if missing.
Pascal Krietec9c045a2011-04-05 14:50:41 -0400787 */
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200788 $str = preg_replace('#(&\#x?)([0-9A-F]+);?#i', '\\1\\2;', $str);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400789
790 /*
791 * Un-Protect GET variables in URLs
792 */
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200793 return str_replace($this->xss_hash(), '&', $str);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400794 }
795
796 // ----------------------------------------------------------------------
797
798 /**
799 * Do Never Allowed
800 *
801 * A utility function for xss_clean()
802 *
803 * @param string
804 * @return string
805 */
806 protected function _do_never_allowed($str)
807 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200808 $str = str_replace(array_keys($this->_never_allowed_str), $this->_never_allowed_str, $str);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400809
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200810 foreach ($this->_never_allowed_regex as $regex)
Pascal Krietec9c045a2011-04-05 14:50:41 -0400811 {
Wes Baker5335bc32012-04-24 15:17:14 -0400812 $str = preg_replace('#'.$regex.'#is', '[removed]', $str);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400813 }
David Behler07b53422011-08-15 00:25:06 +0200814
Pascal Krietec9c045a2011-04-05 14:50:41 -0400815 return $str;
816 }
817
818 // --------------------------------------------------------------------
819
820 /**
821 * Set Cross Site Request Forgery Protection Cookie
822 *
823 * @return string
824 */
825 protected function _csrf_set_hash()
826 {
827 if ($this->_csrf_hash == '')
828 {
David Behler07b53422011-08-15 00:25:06 +0200829 // If the cookie exists we will use it's value.
Pascal Krietec9c045a2011-04-05 14:50:41 -0400830 // We don't necessarily want to regenerate it with
David Behler07b53422011-08-15 00:25:06 +0200831 // each page load since a page could contain embedded
Pascal Krietec9c045a2011-04-05 14:50:41 -0400832 // sub-pages causing this feature to fail
David Behler07b53422011-08-15 00:25:06 +0200833 if (isset($_COOKIE[$this->_csrf_cookie_name]) &&
Pascal Krietec9c045a2011-04-05 14:50:41 -0400834 $_COOKIE[$this->_csrf_cookie_name] != '')
835 {
836 return $this->_csrf_hash = $_COOKIE[$this->_csrf_cookie_name];
837 }
David Behler07b53422011-08-15 00:25:06 +0200838
Chris Berthed93e6f32011-09-25 10:33:25 -0400839 $this->_csrf_hash = md5(uniqid(rand(), TRUE));
840 $this->csrf_set_cookie();
Pascal Krietec9c045a2011-04-05 14:50:41 -0400841 }
842
843 return $this->_csrf_hash;
844 }
845
Derek Jonese701d762010-03-02 18:17:01 -0600846}
Derek Jonese701d762010-03-02 18:17:01 -0600847
848/* End of file Security.php */
Andrey Andreev92ebfb62012-05-17 12:49:24 +0300849/* Location: ./system/core/Security.php */