blob: 1007f61f456f941d281cf2e6ffa732e8585f3a4e [file] [log] [blame]
Andrey Andreevbb488dc2012-01-07 23:35:16 +02001<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
Derek Jonese701d762010-03-02 18:17:01 -06002/**
3 * CodeIgniter
4 *
Greg Aker741de1c2010-11-10 14:52:57 -06005 * An open source application development framework for PHP 5.1.6 or newer
Derek Jonese701d762010-03-02 18:17:01 -06006 *
Derek Jonesf4a4bd82011-10-20 12:18:42 -05007 * NOTICE OF LICENSE
Andrey Andreevbb488dc2012-01-07 23:35:16 +02008 *
Derek Jonesf4a4bd82011-10-20 12:18:42 -05009 * Licensed under the Open Software License version 3.0
Andrey Andreevbb488dc2012-01-07 23:35:16 +020010 *
Derek Jonesf4a4bd82011-10-20 12:18:42 -050011 * This source file is subject to the Open Software License (OSL 3.0) that is
12 * bundled with this package in the files license.txt / license.rst. It is
13 * also available through the world wide web at this URL:
14 * http://opensource.org/licenses/OSL-3.0
15 * If you did not receive a copy of the license and are unable to obtain it
16 * through the world wide web, please send an email to
17 * licensing@ellislab.com so we can send you a copy immediately.
18 *
Derek Jonese701d762010-03-02 18:17:01 -060019 * @package CodeIgniter
Derek Jonesf4a4bd82011-10-20 12:18:42 -050020 * @author EllisLab Dev Team
Greg Aker0defe5d2012-01-01 18:46:41 -060021 * @copyright Copyright (c) 2008 - 2012, EllisLab, Inc. (http://ellislab.com/)
Derek Jonesf4a4bd82011-10-20 12:18:42 -050022 * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
Derek Jonese701d762010-03-02 18:17:01 -060023 * @link http://codeigniter.com
24 * @since Version 1.0
25 * @filesource
26 */
27
28// ------------------------------------------------------------------------
29
30/**
31 * Security Class
32 *
33 * @package CodeIgniter
34 * @subpackage Libraries
35 * @category Security
Derek Jonesf4a4bd82011-10-20 12:18:42 -050036 * @author EllisLab Dev Team
Pascal Krietec9c045a2011-04-05 14:50:41 -040037 * @link http://codeigniter.com/user_guide/libraries/security.html
Derek Jonese701d762010-03-02 18:17:01 -060038 */
39class CI_Security {
Barry Mienydd671972010-10-04 16:33:58 +020040
David Behler07b53422011-08-15 00:25:06 +020041 /**
42 * Random Hash for protecting URLs
43 *
44 * @var string
David Behler07b53422011-08-15 00:25:06 +020045 */
46 protected $_xss_hash = '';
Andrey Andreev3d113bd2011-10-05 00:03:20 +030047
David Behler07b53422011-08-15 00:25:06 +020048 /**
49 * Random Hash for Cross Site Request Forgery Protection Cookie
50 *
51 * @var string
David Behler07b53422011-08-15 00:25:06 +020052 */
53 protected $_csrf_hash = '';
Andrey Andreev3d113bd2011-10-05 00:03:20 +030054
David Behler07b53422011-08-15 00:25:06 +020055 /**
56 * Expiration time for Cross Site Request Forgery Protection Cookie
57 * Defaults to two hours (in seconds)
58 *
59 * @var int
David Behler07b53422011-08-15 00:25:06 +020060 */
61 protected $_csrf_expire = 7200;
Andrey Andreev3d113bd2011-10-05 00:03:20 +030062
David Behler07b53422011-08-15 00:25:06 +020063 /**
64 * Token name for Cross Site Request Forgery Protection Cookie
65 *
66 * @var string
David Behler07b53422011-08-15 00:25:06 +020067 */
68 protected $_csrf_token_name = 'ci_csrf_token';
Andrey Andreev3d113bd2011-10-05 00:03:20 +030069
David Behler07b53422011-08-15 00:25:06 +020070 /**
71 * Cookie name for Cross Site Request Forgery Protection Cookie
72 *
73 * @var string
David Behler07b53422011-08-15 00:25:06 +020074 */
Andrey Andreevbb488dc2012-01-07 23:35:16 +020075 protected $_csrf_cookie_name = 'ci_csrf_token';
Andrey Andreev3d113bd2011-10-05 00:03:20 +030076
David Behler07b53422011-08-15 00:25:06 +020077 /**
78 * List of never allowed strings
79 *
80 * @var array
David Behler07b53422011-08-15 00:25:06 +020081 */
Pascal Krietec9c045a2011-04-05 14:50:41 -040082 protected $_never_allowed_str = array(
Andrey Andreevbb488dc2012-01-07 23:35:16 +020083 'document.cookie' => '[removed]',
84 'document.write' => '[removed]',
85 '.parentNode' => '[removed]',
86 '.innerHTML' => '[removed]',
87 'window.location' => '[removed]',
88 '-moz-binding' => '[removed]',
89 '<!--' => '&lt;!--',
90 '-->' => '--&gt;',
91 '<![CDATA[' => '&lt;![CDATA[',
92 '<comment>' => '&lt;comment&gt;'
93 );
Derek Jonese701d762010-03-02 18:17:01 -060094
David Behler07b53422011-08-15 00:25:06 +020095 /**
96 * List of never allowed regex replacement
97 *
98 * @var array
David Behler07b53422011-08-15 00:25:06 +020099 */
Pascal Krietec9c045a2011-04-05 14:50:41 -0400100 protected $_never_allowed_regex = array(
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200101 'javascript\s*:',
102 'expression\s*(\(|&\#40;)', // CSS and IE
103 'vbscript\s*:', // IE, surprise!
104 'Redirect\s+302'
105 );
David Behler07b53422011-08-15 00:25:06 +0200106
Greg Akera9263282010-11-10 15:26:43 -0600107 public function __construct()
Derek Jonese701d762010-03-02 18:17:01 -0600108 {
patworkef1a55a2011-04-09 13:04:06 +0200109 // CSRF config
110 foreach(array('csrf_expire', 'csrf_token_name', 'csrf_cookie_name') as $key)
111 {
112 if (FALSE !== ($val = config_item($key)))
113 {
114 $this->{'_'.$key} = $val;
115 }
116 }
117
patwork9e267982011-04-11 13:02:32 +0200118 // Append application specific cookie prefix
Greg Akerb3e614d2011-04-19 20:19:17 -0500119 if (config_item('cookie_prefix'))
120 {
patwork9e267982011-04-11 13:02:32 +0200121 $this->_csrf_cookie_name = config_item('cookie_prefix').$this->_csrf_cookie_name;
122 }
Derek Jonesb3f10a22010-07-25 19:11:26 -0500123
Derek Jonese701d762010-03-02 18:17:01 -0600124 // Set the CSRF hash
125 $this->_csrf_set_hash();
Derek Allard958543a2010-07-22 14:10:26 -0400126
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200127 log_message('debug', 'Security Class Initialized');
Derek Jonese701d762010-03-02 18:17:01 -0600128 }
129
130 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200131
Derek Jonese701d762010-03-02 18:17:01 -0600132 /**
133 * Verify Cross Site Request Forgery Protection
134 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400135 * @return object
Derek Jonese701d762010-03-02 18:17:01 -0600136 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500137 public function csrf_verify()
Derek Allard958543a2010-07-22 14:10:26 -0400138 {
Derek Jonese701d762010-03-02 18:17:01 -0600139 // If no POST data exists we will set the CSRF cookie
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200140 if (count($_POST) === 0)
Derek Jonese701d762010-03-02 18:17:01 -0600141 {
142 return $this->csrf_set_cookie();
143 }
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300144
Alex Bilbieaeb2c3e2011-08-21 16:14:54 +0100145 // Check if URI has been whitelisted from CSRF checks
146 if ($exclude_uris = config_item('csrf_exclude_uris'))
147 {
148 $uri = load_class('URI', 'core');
149 if (in_array($uri->uri_string(), $exclude_uris))
150 {
151 return $this;
152 }
153 }
Derek Jonese701d762010-03-02 18:17:01 -0600154
155 // Do the tokens exist in both the _POST and _COOKIE arrays?
Andrey Andreev4562f2c2012-01-09 23:39:50 +0200156 if ( ! isset($_POST[$this->_csrf_token_name]) OR ! isset($_COOKIE[$this->_csrf_cookie_name])
157 OR $_POST[$this->_csrf_token_name] != $_COOKIE[$this->_csrf_cookie_name]) // Do the tokens match?
Derek Jonese701d762010-03-02 18:17:01 -0600158 {
159 $this->csrf_show_error();
160 }
161
Andrey Andreev4562f2c2012-01-09 23:39:50 +0200162 // We kill this since we're done and we don't want to polute the _POST array
Pascal Krietec9c045a2011-04-05 14:50:41 -0400163 unset($_POST[$this->_csrf_token_name]);
Barry Mienydd671972010-10-04 16:33:58 +0200164
RS712be25a62011-12-31 16:02:04 -0200165 // Regenerate on every submission?
166 if (config_item('csrf_regenerate'))
167 {
168 // Nothing should last forever
169 unset($_COOKIE[$this->_csrf_cookie_name]);
170 $this->_csrf_hash = '';
171 }
Andrey Andreev8a7d0782012-01-08 05:43:42 +0200172
Derek Jonesb3f10a22010-07-25 19:11:26 -0500173 $this->_csrf_set_hash();
174 $this->csrf_set_cookie();
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300175
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200176 log_message('debug', 'CSRF token verified');
Pascal Krietec9c045a2011-04-05 14:50:41 -0400177 return $this;
Derek Jonese701d762010-03-02 18:17:01 -0600178 }
Barry Mienydd671972010-10-04 16:33:58 +0200179
Derek Jonese701d762010-03-02 18:17:01 -0600180 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200181
Derek Jonese701d762010-03-02 18:17:01 -0600182 /**
183 * Set Cross Site Request Forgery Protection Cookie
184 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400185 * @return object
Derek Jonese701d762010-03-02 18:17:01 -0600186 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500187 public function csrf_set_cookie()
Derek Jonese701d762010-03-02 18:17:01 -0600188 {
Pascal Krietec9c045a2011-04-05 14:50:41 -0400189 $expire = time() + $this->_csrf_expire;
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300190 $secure_cookie = (bool) config_item('cookie_secure');
Derek Jonese701d762010-03-02 18:17:01 -0600191
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200192 if ($secure_cookie && ( ! isset($_SERVER['HTTPS']) OR $_SERVER['HTTPS'] == 'off' OR ! $_SERVER['HTTPS']))
Derek Jonese701d762010-03-02 18:17:01 -0600193 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200194 return FALSE;
Derek Jonese701d762010-03-02 18:17:01 -0600195 }
Derek Allard958543a2010-07-22 14:10:26 -0400196
Pascal Krietec9c045a2011-04-05 14:50:41 -0400197 setcookie($this->_csrf_cookie_name, $this->_csrf_hash, $expire, config_item('cookie_path'), config_item('cookie_domain'), $secure_cookie);
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200198 log_message('debug', 'CRSF cookie Set');
David Behler07b53422011-08-15 00:25:06 +0200199
Pascal Krietec9c045a2011-04-05 14:50:41 -0400200 return $this;
Derek Jonese701d762010-03-02 18:17:01 -0600201 }
202
203 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200204
Derek Jonese701d762010-03-02 18:17:01 -0600205 /**
206 * Show CSRF Error
207 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400208 * @return void
Derek Jonese701d762010-03-02 18:17:01 -0600209 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500210 public function csrf_show_error()
Derek Jonese701d762010-03-02 18:17:01 -0600211 {
212 show_error('The action you have requested is not allowed.');
213 }
214
215 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200216
Derek Jonese701d762010-03-02 18:17:01 -0600217 /**
David Behler07b53422011-08-15 00:25:06 +0200218 * Get CSRF Hash
Pascal Krietec9c045a2011-04-05 14:50:41 -0400219 *
David Behler07b53422011-08-15 00:25:06 +0200220 * Getter Method
Pascal Krietec9c045a2011-04-05 14:50:41 -0400221 *
222 * @return string self::_csrf_hash
223 */
224 public function get_csrf_hash()
225 {
226 return $this->_csrf_hash;
227 }
228
229 // --------------------------------------------------------------------
230
231 /**
232 * Get CSRF Token Name
233 *
234 * Getter Method
235 *
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200236 * @return string self::_csrf_token_name
Pascal Krietec9c045a2011-04-05 14:50:41 -0400237 */
238 public function get_csrf_token_name()
239 {
240 return $this->_csrf_token_name;
241 }
242
243 // --------------------------------------------------------------------
244
245 /**
Derek Jonese701d762010-03-02 18:17:01 -0600246 * XSS Clean
247 *
248 * Sanitizes data so that Cross Site Scripting Hacks can be
Derek Jones37f4b9c2011-07-01 17:56:50 -0500249 * prevented. This function does a fair amount of work but
Derek Jonese701d762010-03-02 18:17:01 -0600250 * it is extremely thorough, designed to prevent even the
Derek Jones37f4b9c2011-07-01 17:56:50 -0500251 * most obscure XSS attempts. Nothing is ever 100% foolproof,
Derek Jonese701d762010-03-02 18:17:01 -0600252 * of course, but I haven't been able to get anything passed
253 * the filter.
254 *
255 * Note: This function should only be used to deal with data
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200256 * upon submission. It's not something that should
Derek Jonese701d762010-03-02 18:17:01 -0600257 * be used for general runtime processing.
258 *
259 * This function was based in part on some code and ideas I
260 * got from Bitflux: http://channel.bitflux.ch/wiki/XSS_Prevention
261 *
262 * To help develop this script I used this great list of
263 * vulnerabilities along with a few other hacks I've
264 * harvested from examining vulnerabilities in other programs:
265 * http://ha.ckers.org/xss.html
266 *
Derek Jonese701d762010-03-02 18:17:01 -0600267 * @param mixed string or array
David Behler07b53422011-08-15 00:25:06 +0200268 * @param bool
Derek Jonese701d762010-03-02 18:17:01 -0600269 * @return string
270 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500271 public function xss_clean($str, $is_image = FALSE)
Derek Jonese701d762010-03-02 18:17:01 -0600272 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200273 // Is the string an array?
Derek Jonese701d762010-03-02 18:17:01 -0600274 if (is_array($str))
275 {
276 while (list($key) = each($str))
277 {
278 $str[$key] = $this->xss_clean($str[$key]);
279 }
Barry Mienydd671972010-10-04 16:33:58 +0200280
Derek Jonese701d762010-03-02 18:17:01 -0600281 return $str;
282 }
283
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200284 // Remove Invisible Characters and validate entities in URLs
285 $str = $this->_validate_entities(remove_invisible_characters($str));
Derek Jonese701d762010-03-02 18:17:01 -0600286
287 /*
288 * URL Decode
289 *
290 * Just in case stuff like this is submitted:
291 *
292 * <a href="http://%77%77%77%2E%67%6F%6F%67%6C%65%2E%63%6F%6D">Google</a>
293 *
294 * Note: Use rawurldecode() so it does not remove plus signs
Derek Jonese701d762010-03-02 18:17:01 -0600295 */
296 $str = rawurldecode($str);
Barry Mienydd671972010-10-04 16:33:58 +0200297
Derek Jonese701d762010-03-02 18:17:01 -0600298 /*
Barry Mienydd671972010-10-04 16:33:58 +0200299 * Convert character entities to ASCII
Derek Jonese701d762010-03-02 18:17:01 -0600300 *
301 * This permits our tests below to work reliably.
302 * We only convert entities that are within tags since
303 * these are the ones that will pose security problems.
Derek Jonese701d762010-03-02 18:17:01 -0600304 */
Derek Jonese701d762010-03-02 18:17:01 -0600305 $str = preg_replace_callback("/[a-z]+=([\'\"]).*?\\1/si", array($this, '_convert_attribute'), $str);
Andrey Andreev4562f2c2012-01-09 23:39:50 +0200306 $str = preg_replace_callback('/<\w+.*?(?=>|<|$)/si', array($this, '_decode_entity'), $str);
Derek Jonese701d762010-03-02 18:17:01 -0600307
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200308 // Remove Invisible Characters Again!
Greg Aker757dda62010-04-14 19:06:19 -0500309 $str = remove_invisible_characters($str);
Barry Mienydd671972010-10-04 16:33:58 +0200310
Derek Jonese701d762010-03-02 18:17:01 -0600311 /*
312 * Convert all tabs to spaces
313 *
314 * This prevents strings like this: ja vascript
315 * NOTE: we deal with spaces between characters later.
David Behler07b53422011-08-15 00:25:06 +0200316 * NOTE: preg_replace was found to be amazingly slow here on
Pascal Krietec9c045a2011-04-05 14:50:41 -0400317 * large blocks of data, so we use str_replace.
Derek Jonese701d762010-03-02 18:17:01 -0600318 */
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200319 $str = str_replace("\t", ' ', $str);
Barry Mienydd671972010-10-04 16:33:58 +0200320
Andrey Andreev4562f2c2012-01-09 23:39:50 +0200321 // Capture converted string for later comparison
Derek Jonese701d762010-03-02 18:17:01 -0600322 $converted_string = $str;
Barry Mienydd671972010-10-04 16:33:58 +0200323
Pascal Krietec9c045a2011-04-05 14:50:41 -0400324 // Remove Strings that are never allowed
325 $str = $this->_do_never_allowed($str);
Derek Jonese701d762010-03-02 18:17:01 -0600326
327 /*
328 * Makes PHP tags safe
329 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400330 * Note: XML tags are inadvertently replaced too:
Derek Jonese701d762010-03-02 18:17:01 -0600331 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400332 * <?xml
Derek Jonese701d762010-03-02 18:17:01 -0600333 *
334 * But it doesn't seem to pose a problem.
Derek Jonese701d762010-03-02 18:17:01 -0600335 */
336 if ($is_image === TRUE)
337 {
David Behler07b53422011-08-15 00:25:06 +0200338 // Images have a tendency to have the PHP short opening and
339 // closing tags every so often so we skip those and only
Pascal Krietec9c045a2011-04-05 14:50:41 -0400340 // do the long opening tags.
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200341 $str = preg_replace('/<\?(php)/i', '&lt;?\\1', $str);
Derek Jonese701d762010-03-02 18:17:01 -0600342 }
343 else
344 {
Derek Jones37f4b9c2011-07-01 17:56:50 -0500345 $str = str_replace(array('<?', '?'.'>'), array('&lt;?', '?&gt;'), $str);
Derek Jonese701d762010-03-02 18:17:01 -0600346 }
Barry Mienydd671972010-10-04 16:33:58 +0200347
Derek Jonese701d762010-03-02 18:17:01 -0600348 /*
349 * Compact any exploded words
350 *
Derek Jones37f4b9c2011-07-01 17:56:50 -0500351 * This corrects words like: j a v a s c r i p t
Derek Jonese701d762010-03-02 18:17:01 -0600352 * These words are compacted back to their correct state.
Derek Jonese701d762010-03-02 18:17:01 -0600353 */
Pascal Krietec9c045a2011-04-05 14:50:41 -0400354 $words = array(
David Behler07b53422011-08-15 00:25:06 +0200355 'javascript', 'expression', 'vbscript', 'script',
Pascal Krietec9c045a2011-04-05 14:50:41 -0400356 'applet', 'alert', 'document', 'write', 'cookie', 'window'
357 );
David Behler07b53422011-08-15 00:25:06 +0200358
Derek Jonese701d762010-03-02 18:17:01 -0600359 foreach ($words as $word)
360 {
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300361 $word = implode("\s*", str_split($word)) . "\s*";
Derek Jonese701d762010-03-02 18:17:01 -0600362
363 // We only want to do this when it is followed by a non-word character
364 // That way valid stuff like "dealer to" does not become "dealerto"
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300365 $str = preg_replace_callback('#('.substr($word, 0, -3).')(\W)#is', array($this, '_compact_exploded_words'), $str);
Derek Jonese701d762010-03-02 18:17:01 -0600366 }
Barry Mienydd671972010-10-04 16:33:58 +0200367
Derek Jonese701d762010-03-02 18:17:01 -0600368 /*
369 * Remove disallowed Javascript in links or img tags
David Behler07b53422011-08-15 00:25:06 +0200370 * We used to do some version comparisons and use of stripos for PHP5,
371 * but it is dog slow compared to these simplified non-capturing
Pascal Krietec9c045a2011-04-05 14:50:41 -0400372 * preg_match(), especially if the pattern exists in the string
Derek Jonese701d762010-03-02 18:17:01 -0600373 */
374 do
375 {
376 $original = $str;
Barry Mienydd671972010-10-04 16:33:58 +0200377
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200378 if (preg_match('/<a/i', $str))
Derek Jonese701d762010-03-02 18:17:01 -0600379 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200380 $str = preg_replace_callback('#<a\s+([^>]*?)(>|$)#si', array($this, '_js_link_removal'), $str);
Derek Jonese701d762010-03-02 18:17:01 -0600381 }
Barry Mienydd671972010-10-04 16:33:58 +0200382
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200383 if (preg_match('/<img/i', $str))
Derek Jonese701d762010-03-02 18:17:01 -0600384 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200385 $str = preg_replace_callback('#<img\s+([^>]*?)(\s?/?>|$)#si', array($this, '_js_img_removal'), $str);
Derek Jonese701d762010-03-02 18:17:01 -0600386 }
Barry Mienydd671972010-10-04 16:33:58 +0200387
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200388 if (preg_match('/(script|xss)/i', $str))
Derek Jonese701d762010-03-02 18:17:01 -0600389 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200390 $str = preg_replace('#<(/*)(script|xss)(.*?)\>#si', '[removed]', $str);
Derek Jonese701d762010-03-02 18:17:01 -0600391 }
392 }
Pascal Krietec9c045a2011-04-05 14:50:41 -0400393 while($original != $str);
Derek Jonese701d762010-03-02 18:17:01 -0600394
395 unset($original);
396
Pascal Krietec9c045a2011-04-05 14:50:41 -0400397 // Remove evil attributes such as style, onclick and xmlns
398 $str = $this->_remove_evil_attributes($str, $is_image);
Barry Mienydd671972010-10-04 16:33:58 +0200399
Derek Jonese701d762010-03-02 18:17:01 -0600400 /*
401 * Sanitize naughty HTML elements
402 *
403 * If a tag containing any of the words in the list
404 * below is found, the tag gets converted to entities.
405 *
406 * So this: <blink>
407 * Becomes: &lt;blink&gt;
Derek Jonese701d762010-03-02 18:17:01 -0600408 */
409 $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';
410 $str = preg_replace_callback('#<(/*\s*)('.$naughty.')([^><]*)([><]*)#is', array($this, '_sanitize_naughty_html'), $str);
411
412 /*
413 * Sanitize naughty scripting elements
414 *
415 * Similar to above, only instead of looking for
416 * tags it looks for PHP and JavaScript commands
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200417 * that are disallowed. Rather than removing the
Derek Jonese701d762010-03-02 18:17:01 -0600418 * code, it simply converts the parenthesis to entities
419 * rendering the code un-executable.
420 *
421 * For example: eval('some code')
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200422 * Becomes: eval&#40;'some code'&#41;
Derek Jonese701d762010-03-02 18:17:01 -0600423 */
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200424 $str = preg_replace('#(alert|cmd|passthru|eval|exec|expression|system|fopen|fsockopen|file|file_get_contents|readfile|unlink)(\s*)\((.*?)\)#si',
425 '\\1\\2&#40;\\3&#41;',
426 $str);
Barry Mienydd671972010-10-04 16:33:58 +0200427
Barry Mienydd671972010-10-04 16:33:58 +0200428
Pascal Krietec9c045a2011-04-05 14:50:41 -0400429 // Final clean up
430 // This adds a bit of extra precaution in case
431 // something got through the above filters
432 $str = $this->_do_never_allowed($str);
Derek Jonese701d762010-03-02 18:17:01 -0600433
434 /*
Pascal Krietec9c045a2011-04-05 14:50:41 -0400435 * Images are Handled in a Special Way
David Behler07b53422011-08-15 00:25:06 +0200436 * - Essentially, we want to know that after all of the character
437 * conversion is done whether any unwanted, likely XSS, code was found.
Pascal Krietec9c045a2011-04-05 14:50:41 -0400438 * If not, we return TRUE, as the image is clean.
David Behler07b53422011-08-15 00:25:06 +0200439 * However, if the string post-conversion does not matched the
440 * string post-removal of XSS, then it fails, as there was unwanted XSS
Pascal Krietec9c045a2011-04-05 14:50:41 -0400441 * code found and removed/changed during processing.
Derek Jonese701d762010-03-02 18:17:01 -0600442 */
Derek Jonese701d762010-03-02 18:17:01 -0600443 if ($is_image === TRUE)
444 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200445 return ($str === $converted_string);
Derek Jonese701d762010-03-02 18:17:01 -0600446 }
Barry Mienydd671972010-10-04 16:33:58 +0200447
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200448 log_message('debug', 'XSS Filtering completed');
Derek Jonese701d762010-03-02 18:17:01 -0600449 return $str;
450 }
451
452 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200453
Derek Jonese701d762010-03-02 18:17:01 -0600454 /**
455 * Random Hash for protecting URLs
456 *
Derek Jonese701d762010-03-02 18:17:01 -0600457 * @return string
458 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500459 public function xss_hash()
Barry Mienydd671972010-10-04 16:33:58 +0200460 {
Pascal Krietec9c045a2011-04-05 14:50:41 -0400461 if ($this->_xss_hash == '')
Derek Jonese701d762010-03-02 18:17:01 -0600462 {
Pascal Krietec38e3b62011-11-14 13:55:00 -0500463 mt_srand();
Pascal Krietec9c045a2011-04-05 14:50:41 -0400464 $this->_xss_hash = md5(time() + mt_rand(0, 1999999999));
Derek Jonese701d762010-03-02 18:17:01 -0600465 }
466
Pascal Krietec9c045a2011-04-05 14:50:41 -0400467 return $this->_xss_hash;
Derek Jonese701d762010-03-02 18:17:01 -0600468 }
469
470 // --------------------------------------------------------------------
471
472 /**
Derek Jonesa0911472010-03-30 10:33:09 -0500473 * HTML Entities Decode
474 *
475 * This function is a replacement for html_entity_decode()
476 *
Pascal Krietec38e3b62011-11-14 13:55:00 -0500477 * The reason we are not using html_entity_decode() by itself is because
478 * while it is not technically correct to leave out the semicolon
479 * at the end of an entity most browsers will still interpret the entity
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200480 * correctly. html_entity_decode() does not convert entities without
Pascal Krietec38e3b62011-11-14 13:55:00 -0500481 * semicolons, so we are left with our own little solution here. Bummer.
Derek Jonesa0911472010-03-30 10:33:09 -0500482 *
Derek Jonesa0911472010-03-30 10:33:09 -0500483 * @param string
484 * @param string
485 * @return string
486 */
freewil8cc0cfe2011-08-27 21:53:00 -0400487 public function entity_decode($str, $charset = NULL)
Derek Jonesa0911472010-03-30 10:33:09 -0500488 {
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300489 if (strpos($str, '&') === FALSE)
freewil5c9b0d12011-08-28 12:15:23 -0400490 {
491 return $str;
492 }
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300493
freewil5c9b0d12011-08-28 12:15:23 -0400494 if (empty($charset))
495 {
496 $charset = config_item('charset');
497 }
Barry Mienydd671972010-10-04 16:33:58 +0200498
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300499 $str = html_entity_decode($str, ENT_COMPAT, $charset);
500 $str = preg_replace('~&#x(0*[0-9a-f]{2,5})~ei', 'chr(hexdec("\\1"))', $str);
501 return preg_replace('~&#([0-9]{2,4})~e', 'chr(\\1)', $str);
Derek Jonesa0911472010-03-30 10:33:09 -0500502 }
Barry Mienydd671972010-10-04 16:33:58 +0200503
Derek Jonesa0911472010-03-30 10:33:09 -0500504 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200505
Derek Jonesa0911472010-03-30 10:33:09 -0500506 /**
Derek Jonese701d762010-03-02 18:17:01 -0600507 * Filename Security
508 *
Derek Jonese701d762010-03-02 18:17:01 -0600509 * @param string
David Behler07b53422011-08-15 00:25:06 +0200510 * @param bool
Derek Jonese701d762010-03-02 18:17:01 -0600511 * @return string
512 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500513 public function sanitize_filename($str, $relative_path = FALSE)
Derek Jonese701d762010-03-02 18:17:01 -0600514 {
515 $bad = array(
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200516 '../', '<!--', '-->', '<', '>',
517 "'", '"', '&', '$', '#',
518 '{', '}', '[', ']', '=',
519 ';', '?', '%20', '%22',
520 '%3c', // <
521 '%253c', // <
522 '%3e', // >
523 '%0e', // >
524 '%28', // (
525 '%29', // )
526 '%2528', // (
527 '%26', // &
528 '%24', // $
529 '%3f', // ?
530 '%3b', // ;
531 '%3d' // =
532 );
David Behler07b53422011-08-15 00:25:06 +0200533
Derek Jones2ef37592010-10-06 17:51:59 -0500534 if ( ! $relative_path)
535 {
536 $bad[] = './';
537 $bad[] = '/';
538 }
Derek Jonese701d762010-03-02 18:17:01 -0600539
Pascal Krietec9c045a2011-04-05 14:50:41 -0400540 $str = remove_invisible_characters($str, FALSE);
Derek Jonese701d762010-03-02 18:17:01 -0600541 return stripslashes(str_replace($bad, '', $str));
542 }
543
Pascal Krietec9c045a2011-04-05 14:50:41 -0400544 // ----------------------------------------------------------------
545
546 /**
547 * Compact Exploded Words
548 *
549 * Callback function for xss_clean() to remove whitespace from
550 * things like j a v a s c r i p t
551 *
552 * @param type
553 * @return type
554 */
555 protected function _compact_exploded_words($matches)
556 {
557 return preg_replace('/\s+/s', '', $matches[1]).$matches[2];
558 }
559
560 // --------------------------------------------------------------------
David Behler07b53422011-08-15 00:25:06 +0200561
Pascal Krietec9c045a2011-04-05 14:50:41 -0400562 /*
563 * Remove Evil HTML Attributes (like evenhandlers and style)
564 *
565 * It removes the evil attribute and either:
566 * - Everything up until a space
567 * For example, everything between the pipes:
568 * <a |style=document.write('hello');alert('world');| class=link>
David Behler07b53422011-08-15 00:25:06 +0200569 * - Everything inside the quotes
Pascal Krietec9c045a2011-04-05 14:50:41 -0400570 * For example, everything between the pipes:
571 * <a |style="document.write('hello'); alert('world');"| class="link">
572 *
573 * @param string $str The string to check
574 * @param boolean $is_image TRUE if this is an image
575 * @return string The string with the evil attributes removed
576 */
577 protected function _remove_evil_attributes($str, $is_image)
578 {
579 // All javascript event handlers (e.g. onload, onclick, onmouseover), style, and xmlns
Pascal Krietec38e3b62011-11-14 13:55:00 -0500580 $evil_attributes = array('on\w*', 'style', 'xmlns', 'formaction');
Pascal Krietec9c045a2011-04-05 14:50:41 -0400581
582 if ($is_image === TRUE)
583 {
584 /*
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200585 * Adobe Photoshop puts XML metadata into JFIF images,
Pascal Krietec9c045a2011-04-05 14:50:41 -0400586 * including namespacing, so we have to allow this for images.
587 */
588 unset($evil_attributes[array_search('xmlns', $evil_attributes)]);
589 }
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200590
Pascal Krietec9c045a2011-04-05 14:50:41 -0400591 do {
Pascal Krietec38e3b62011-11-14 13:55:00 -0500592 $count = 0;
593 $attribs = array();
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200594
Pascal Krietec38e3b62011-11-14 13:55:00 -0500595 // find occurrences of illegal attribute strings without quotes
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200596 preg_match_all('/('.implode('|', $evil_attributes).')\s*=\s*([^\s]*)/is', $str, $matches, PREG_SET_ORDER);
597
Pascal Krietec38e3b62011-11-14 13:55:00 -0500598 foreach ($matches as $attr)
599 {
600 $attribs[] = preg_quote($attr[0], '/');
601 }
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200602
Pascal Krietec38e3b62011-11-14 13:55:00 -0500603 // find occurrences of illegal attribute strings with quotes (042 and 047 are octal quotes)
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200604 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 +0200605
Pascal Krietec38e3b62011-11-14 13:55:00 -0500606 foreach ($matches as $attr)
607 {
608 $attribs[] = preg_quote($attr[0], '/');
609 }
610
611 // replace illegal attribute strings that are inside an html tag
612 if (count($attribs) > 0)
613 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200614 $str = preg_replace('/<(\/?[^><]+?)([^A-Za-z\-])('.implode('|', $attribs).')([\s><])([><]*)/i', '<$1$2$4$5', $str, -1, $count);
Pascal Krietec38e3b62011-11-14 13:55:00 -0500615 }
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200616
Pascal Krietec38e3b62011-11-14 13:55:00 -0500617 } while ($count);
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200618
Pascal Krietec9c045a2011-04-05 14:50:41 -0400619 return $str;
620 }
David Behler07b53422011-08-15 00:25:06 +0200621
Pascal Krietec9c045a2011-04-05 14:50:41 -0400622 // --------------------------------------------------------------------
623
624 /**
625 * Sanitize Naughty HTML
626 *
627 * Callback function for xss_clean() to remove naughty HTML elements
628 *
629 * @param array
630 * @return string
631 */
632 protected function _sanitize_naughty_html($matches)
633 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200634 return '&lt;'.$matches[1].$matches[2].$matches[3] // encode opening brace
635 // encode captured opening or closing brace to prevent recursive vectors:
636 . str_replace(array('>', '<'), array('&gt;', '&lt;'), $matches[4]);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400637 }
638
639 // --------------------------------------------------------------------
640
641 /**
642 * JS Link Removal
643 *
644 * Callback function for xss_clean() to sanitize links
645 * This limits the PCRE backtracks, making it more performance friendly
646 * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in
647 * PHP 5.2+ on link-heavy strings
648 *
649 * @param array
650 * @return string
651 */
652 protected function _js_link_removal($match)
653 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200654 return str_replace($match[1],
655 preg_replace('#href=.*?(alert\(|alert&\#40;|javascript\:|livescript\:|mocha\:|charset\=|window\.|document\.|\.cookie|<script|<xss|base64\s*,)#si',
656 '',
657 $this->_filter_attributes(str_replace(array('<', '>'), '', $match[1]))
658 ),
659 $match[0]);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400660 }
661
662 // --------------------------------------------------------------------
663
664 /**
665 * JS Image Removal
666 *
667 * Callback function for xss_clean() to sanitize image tags
668 * This limits the PCRE backtracks, making it more performance friendly
669 * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in
670 * PHP 5.2+ on image tag heavy strings
671 *
672 * @param array
673 * @return string
674 */
675 protected function _js_img_removal($match)
676 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200677 return str_replace($match[1],
678 preg_replace('#src=.*?(alert\(|alert&\#40;|javascript\:|livescript\:|mocha\:|charset\=|window\.|document\.|\.cookie|<script|<xss|base64\s*,)#si',
679 '',
680 $this->_filter_attributes(str_replace(array('<', '>'), '', $match[1]))
681 ),
682 $match[0]);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400683 }
684
685 // --------------------------------------------------------------------
686
687 /**
688 * Attribute Conversion
689 *
690 * Used as a callback for XSS Clean
691 *
692 * @param array
693 * @return string
694 */
695 protected function _convert_attribute($match)
696 {
697 return str_replace(array('>', '<', '\\'), array('&gt;', '&lt;', '\\\\'), $match[0]);
698 }
699
700 // --------------------------------------------------------------------
701
702 /**
703 * Filter Attributes
704 *
705 * Filters tag attributes for consistency and safety
706 *
707 * @param string
708 * @return string
709 */
710 protected function _filter_attributes($str)
711 {
712 $out = '';
Pascal Krietec9c045a2011-04-05 14:50:41 -0400713 if (preg_match_all('#\s*[a-z\-]+\s*=\s*(\042|\047)([^\\1]*?)\\1#is', $str, $matches))
714 {
715 foreach ($matches[0] as $match)
716 {
Andrey Andreev4562f2c2012-01-09 23:39:50 +0200717 $out .= preg_replace('#/\*.*?\*/#s', '', $match);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400718 }
719 }
720
721 return $out;
722 }
723
724 // --------------------------------------------------------------------
725
726 /**
727 * HTML Entity Decode Callback
728 *
729 * Used as a callback for XSS Clean
730 *
731 * @param array
732 * @return string
733 */
734 protected function _decode_entity($match)
735 {
736 return $this->entity_decode($match[0], strtoupper(config_item('charset')));
737 }
738
739 // --------------------------------------------------------------------
David Behler07b53422011-08-15 00:25:06 +0200740
Pascal Krietec9c045a2011-04-05 14:50:41 -0400741 /**
742 * Validate URL entities
743 *
744 * Called by xss_clean()
745 *
David Behler07b53422011-08-15 00:25:06 +0200746 * @param string
Pascal Krietec9c045a2011-04-05 14:50:41 -0400747 * @return string
748 */
749 protected function _validate_entities($str)
750 {
751 /*
752 * Protect GET variables in URLs
753 */
David Behler07b53422011-08-15 00:25:06 +0200754
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200755 // 901119URL5918AMP18930PROTECT8198
756 $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 -0400757
758 /*
759 * Validate standard character entities
760 *
Derek Jones37f4b9c2011-07-01 17:56:50 -0500761 * Add a semicolon if missing. We do this to enable
Pascal Krietec9c045a2011-04-05 14:50:41 -0400762 * the conversion of entities to ASCII later.
Pascal Krietec9c045a2011-04-05 14:50:41 -0400763 */
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200764 $str = preg_replace('#(&\#?[0-9a-z]{2,})([\x00-\x20])*;?#i', '\\1;\\2', $str);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400765
766 /*
767 * Validate UTF16 two byte encoding (x00)
768 *
769 * Just as above, adds a semicolon if missing.
Pascal Krietec9c045a2011-04-05 14:50:41 -0400770 */
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200771 $str = preg_replace('#(&\#x?)([0-9A-F]+);?#i', '\\1\\2;', $str);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400772
773 /*
774 * Un-Protect GET variables in URLs
775 */
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200776 return str_replace($this->xss_hash(), '&', $str);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400777 }
778
779 // ----------------------------------------------------------------------
780
781 /**
782 * Do Never Allowed
783 *
784 * A utility function for xss_clean()
785 *
786 * @param string
787 * @return string
788 */
789 protected function _do_never_allowed($str)
790 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200791 $str = str_replace(array_keys($this->_never_allowed_str), $this->_never_allowed_str, $str);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400792
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200793 foreach ($this->_never_allowed_regex as $regex)
Pascal Krietec9c045a2011-04-05 14:50:41 -0400794 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200795 $str = preg_replace('#'.$regex.'#i', '[removed]', $str);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400796 }
David Behler07b53422011-08-15 00:25:06 +0200797
Pascal Krietec9c045a2011-04-05 14:50:41 -0400798 return $str;
799 }
800
801 // --------------------------------------------------------------------
802
803 /**
804 * Set Cross Site Request Forgery Protection Cookie
805 *
806 * @return string
807 */
808 protected function _csrf_set_hash()
809 {
810 if ($this->_csrf_hash == '')
811 {
David Behler07b53422011-08-15 00:25:06 +0200812 // If the cookie exists we will use it's value.
Pascal Krietec9c045a2011-04-05 14:50:41 -0400813 // We don't necessarily want to regenerate it with
David Behler07b53422011-08-15 00:25:06 +0200814 // each page load since a page could contain embedded
Pascal Krietec9c045a2011-04-05 14:50:41 -0400815 // sub-pages causing this feature to fail
David Behler07b53422011-08-15 00:25:06 +0200816 if (isset($_COOKIE[$this->_csrf_cookie_name]) &&
Pascal Krietec9c045a2011-04-05 14:50:41 -0400817 $_COOKIE[$this->_csrf_cookie_name] != '')
818 {
819 return $this->_csrf_hash = $_COOKIE[$this->_csrf_cookie_name];
820 }
David Behler07b53422011-08-15 00:25:06 +0200821
Chris Berthed93e6f32011-09-25 10:33:25 -0400822 $this->_csrf_hash = md5(uniqid(rand(), TRUE));
823 $this->csrf_set_cookie();
Pascal Krietec9c045a2011-04-05 14:50:41 -0400824 }
825
826 return $this->_csrf_hash;
827 }
828
Derek Jonese701d762010-03-02 18:17:01 -0600829}
Derek Jonese701d762010-03-02 18:17:01 -0600830
831/* End of file Security.php */
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200832/* Location: ./system/core/Security.php */