blob: 974e2e428b24f9f616d99916a6cf21076066a2a7 [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 */
Timothy Warren48a7fbb2012-04-23 11:58:16 -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!
102 'Redirect\s+302'
103 );
David Behler07b53422011-08-15 00:25:06 +0200104
Timothy Warrenad475052012-04-19 13:21:06 -0400105 /**
106 * Initialize security class
107 */
Greg Akera9263282010-11-10 15:26:43 -0600108 public function __construct()
Derek Jonese701d762010-03-02 18:17:01 -0600109 {
Andrey Andreev67ccdc02012-02-27 23:57:58 +0200110 // Is CSRF protection enabled?
111 if (config_item('csrf_protection') === TRUE)
patworkef1a55a2011-04-09 13:04:06 +0200112 {
Andrey Andreev67ccdc02012-02-27 23:57:58 +0200113 // CSRF config
114 foreach (array('csrf_expire', 'csrf_token_name', 'csrf_cookie_name') as $key)
patworkef1a55a2011-04-09 13:04:06 +0200115 {
Andrey Andreev67ccdc02012-02-27 23:57:58 +0200116 if (FALSE !== ($val = config_item($key)))
117 {
118 $this->{'_'.$key} = $val;
119 }
patworkef1a55a2011-04-09 13:04:06 +0200120 }
patworkef1a55a2011-04-09 13:04:06 +0200121
Andrey Andreev67ccdc02012-02-27 23:57:58 +0200122 // Append application specific cookie prefix
123 if (config_item('cookie_prefix'))
124 {
125 $this->_csrf_cookie_name = config_item('cookie_prefix').$this->_csrf_cookie_name;
126 }
Derek Jonesb3f10a22010-07-25 19:11:26 -0500127
Andrey Andreev67ccdc02012-02-27 23:57:58 +0200128 // Set the CSRF hash
129 $this->_csrf_set_hash();
130 }
Derek Allard958543a2010-07-22 14:10:26 -0400131
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200132 log_message('debug', 'Security Class Initialized');
Derek Jonese701d762010-03-02 18:17:01 -0600133 }
134
135 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200136
Derek Jonese701d762010-03-02 18:17:01 -0600137 /**
138 * Verify Cross Site Request Forgery Protection
139 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400140 * @return object
Derek Jonese701d762010-03-02 18:17:01 -0600141 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500142 public function csrf_verify()
Derek Allard958543a2010-07-22 14:10:26 -0400143 {
Andrey Andreev5d27c432012-03-08 12:01:52 +0200144 // If it's not a POST request we will set the CSRF cookie
145 if (strtoupper($_SERVER['REQUEST_METHOD']) !== 'POST')
Derek Jonese701d762010-03-02 18:17:01 -0600146 {
147 return $this->csrf_set_cookie();
148 }
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300149
Alex Bilbieaeb2c3e2011-08-21 16:14:54 +0100150 // Check if URI has been whitelisted from CSRF checks
151 if ($exclude_uris = config_item('csrf_exclude_uris'))
152 {
153 $uri = load_class('URI', 'core');
154 if (in_array($uri->uri_string(), $exclude_uris))
155 {
156 return $this;
157 }
158 }
Derek Jonese701d762010-03-02 18:17:01 -0600159
160 // Do the tokens exist in both the _POST and _COOKIE arrays?
Andrey Andreev4562f2c2012-01-09 23:39:50 +0200161 if ( ! isset($_POST[$this->_csrf_token_name]) OR ! isset($_COOKIE[$this->_csrf_cookie_name])
162 OR $_POST[$this->_csrf_token_name] != $_COOKIE[$this->_csrf_cookie_name]) // Do the tokens match?
Derek Jonese701d762010-03-02 18:17:01 -0600163 {
164 $this->csrf_show_error();
165 }
166
Andrey Andreev4562f2c2012-01-09 23:39:50 +0200167 // We kill this since we're done and we don't want to polute the _POST array
Pascal Krietec9c045a2011-04-05 14:50:41 -0400168 unset($_POST[$this->_csrf_token_name]);
Barry Mienydd671972010-10-04 16:33:58 +0200169
RS712be25a62011-12-31 16:02:04 -0200170 // Regenerate on every submission?
171 if (config_item('csrf_regenerate'))
172 {
173 // Nothing should last forever
174 unset($_COOKIE[$this->_csrf_cookie_name]);
175 $this->_csrf_hash = '';
176 }
Andrey Andreev8a7d0782012-01-08 05:43:42 +0200177
Derek Jonesb3f10a22010-07-25 19:11:26 -0500178 $this->_csrf_set_hash();
179 $this->csrf_set_cookie();
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300180
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200181 log_message('debug', 'CSRF token verified');
Pascal Krietec9c045a2011-04-05 14:50:41 -0400182 return $this;
Derek Jonese701d762010-03-02 18:17:01 -0600183 }
Barry Mienydd671972010-10-04 16:33:58 +0200184
Derek Jonese701d762010-03-02 18:17:01 -0600185 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200186
Derek Jonese701d762010-03-02 18:17:01 -0600187 /**
188 * Set Cross Site Request Forgery Protection Cookie
189 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400190 * @return object
Derek Jonese701d762010-03-02 18:17:01 -0600191 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500192 public function csrf_set_cookie()
Derek Jonese701d762010-03-02 18:17:01 -0600193 {
Pascal Krietec9c045a2011-04-05 14:50:41 -0400194 $expire = time() + $this->_csrf_expire;
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300195 $secure_cookie = (bool) config_item('cookie_secure');
Derek Jonese701d762010-03-02 18:17:01 -0600196
Andrey Andreeva10c8e12012-02-29 18:56:12 +0200197 if ($secure_cookie && (empty($_SERVER['HTTPS']) OR strtolower($_SERVER['HTTPS']) === 'off'))
Derek Jonese701d762010-03-02 18:17:01 -0600198 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200199 return FALSE;
Derek Jonese701d762010-03-02 18:17:01 -0600200 }
Derek Allard958543a2010-07-22 14:10:26 -0400201
freewil4ad0fd82012-03-13 22:37:42 -0400202 setcookie(
203 $this->_csrf_cookie_name,
204 $this->_csrf_hash,
205 $expire,
206 config_item('cookie_path'),
207 config_item('cookie_domain'),
208 $secure_cookie,
209 config_item('cookie_httponly')
210 );
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200211 log_message('debug', 'CRSF cookie Set');
David Behler07b53422011-08-15 00:25:06 +0200212
Pascal Krietec9c045a2011-04-05 14:50:41 -0400213 return $this;
Derek Jonese701d762010-03-02 18:17:01 -0600214 }
215
216 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200217
Derek Jonese701d762010-03-02 18:17:01 -0600218 /**
219 * Show CSRF Error
220 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400221 * @return void
Derek Jonese701d762010-03-02 18:17:01 -0600222 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500223 public function csrf_show_error()
Derek Jonese701d762010-03-02 18:17:01 -0600224 {
225 show_error('The action you have requested is not allowed.');
226 }
227
228 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200229
Derek Jonese701d762010-03-02 18:17:01 -0600230 /**
David Behler07b53422011-08-15 00:25:06 +0200231 * Get CSRF Hash
Pascal Krietec9c045a2011-04-05 14:50:41 -0400232 *
David Behler07b53422011-08-15 00:25:06 +0200233 * Getter Method
Pascal Krietec9c045a2011-04-05 14:50:41 -0400234 *
235 * @return string self::_csrf_hash
236 */
237 public function get_csrf_hash()
238 {
239 return $this->_csrf_hash;
240 }
241
242 // --------------------------------------------------------------------
243
244 /**
245 * Get CSRF Token Name
246 *
247 * Getter Method
248 *
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200249 * @return string self::_csrf_token_name
Pascal Krietec9c045a2011-04-05 14:50:41 -0400250 */
251 public function get_csrf_token_name()
252 {
253 return $this->_csrf_token_name;
254 }
255
256 // --------------------------------------------------------------------
257
258 /**
Derek Jonese701d762010-03-02 18:17:01 -0600259 * XSS Clean
260 *
261 * Sanitizes data so that Cross Site Scripting Hacks can be
Derek Jones37f4b9c2011-07-01 17:56:50 -0500262 * prevented. This function does a fair amount of work but
Derek Jonese701d762010-03-02 18:17:01 -0600263 * it is extremely thorough, designed to prevent even the
Derek Jones37f4b9c2011-07-01 17:56:50 -0500264 * most obscure XSS attempts. Nothing is ever 100% foolproof,
Derek Jonese701d762010-03-02 18:17:01 -0600265 * of course, but I haven't been able to get anything passed
266 * the filter.
267 *
268 * Note: This function should only be used to deal with data
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200269 * upon submission. It's not something that should
Derek Jonese701d762010-03-02 18:17:01 -0600270 * be used for general runtime processing.
271 *
272 * This function was based in part on some code and ideas I
273 * got from Bitflux: http://channel.bitflux.ch/wiki/XSS_Prevention
274 *
275 * To help develop this script I used this great list of
276 * vulnerabilities along with a few other hacks I've
277 * harvested from examining vulnerabilities in other programs:
278 * http://ha.ckers.org/xss.html
279 *
Derek Jonese701d762010-03-02 18:17:01 -0600280 * @param mixed string or array
David Behler07b53422011-08-15 00:25:06 +0200281 * @param bool
Derek Jonese701d762010-03-02 18:17:01 -0600282 * @return string
283 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500284 public function xss_clean($str, $is_image = FALSE)
Derek Jonese701d762010-03-02 18:17:01 -0600285 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200286 // Is the string an array?
Derek Jonese701d762010-03-02 18:17:01 -0600287 if (is_array($str))
288 {
289 while (list($key) = each($str))
290 {
291 $str[$key] = $this->xss_clean($str[$key]);
292 }
Barry Mienydd671972010-10-04 16:33:58 +0200293
Derek Jonese701d762010-03-02 18:17:01 -0600294 return $str;
295 }
296
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200297 // Remove Invisible Characters and validate entities in URLs
298 $str = $this->_validate_entities(remove_invisible_characters($str));
Derek Jonese701d762010-03-02 18:17:01 -0600299
300 /*
301 * URL Decode
302 *
303 * Just in case stuff like this is submitted:
304 *
305 * <a href="http://%77%77%77%2E%67%6F%6F%67%6C%65%2E%63%6F%6D">Google</a>
306 *
307 * Note: Use rawurldecode() so it does not remove plus signs
Derek Jonese701d762010-03-02 18:17:01 -0600308 */
309 $str = rawurldecode($str);
Barry Mienydd671972010-10-04 16:33:58 +0200310
Derek Jonese701d762010-03-02 18:17:01 -0600311 /*
Barry Mienydd671972010-10-04 16:33:58 +0200312 * Convert character entities to ASCII
Derek Jonese701d762010-03-02 18:17:01 -0600313 *
314 * This permits our tests below to work reliably.
315 * We only convert entities that are within tags since
316 * these are the ones that will pose security problems.
Derek Jonese701d762010-03-02 18:17:01 -0600317 */
Derek Jonese701d762010-03-02 18:17:01 -0600318 $str = preg_replace_callback("/[a-z]+=([\'\"]).*?\\1/si", array($this, '_convert_attribute'), $str);
Andrey Andreev4562f2c2012-01-09 23:39:50 +0200319 $str = preg_replace_callback('/<\w+.*?(?=>|<|$)/si', array($this, '_decode_entity'), $str);
Derek Jonese701d762010-03-02 18:17:01 -0600320
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200321 // Remove Invisible Characters Again!
Greg Aker757dda62010-04-14 19:06:19 -0500322 $str = remove_invisible_characters($str);
Barry Mienydd671972010-10-04 16:33:58 +0200323
Derek Jonese701d762010-03-02 18:17:01 -0600324 /*
325 * Convert all tabs to spaces
326 *
327 * This prevents strings like this: ja vascript
328 * NOTE: we deal with spaces between characters later.
David Behler07b53422011-08-15 00:25:06 +0200329 * NOTE: preg_replace was found to be amazingly slow here on
Pascal Krietec9c045a2011-04-05 14:50:41 -0400330 * large blocks of data, so we use str_replace.
Derek Jonese701d762010-03-02 18:17:01 -0600331 */
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200332 $str = str_replace("\t", ' ', $str);
Barry Mienydd671972010-10-04 16:33:58 +0200333
Andrey Andreev4562f2c2012-01-09 23:39:50 +0200334 // Capture converted string for later comparison
Derek Jonese701d762010-03-02 18:17:01 -0600335 $converted_string = $str;
Barry Mienydd671972010-10-04 16:33:58 +0200336
Pascal Krietec9c045a2011-04-05 14:50:41 -0400337 // Remove Strings that are never allowed
338 $str = $this->_do_never_allowed($str);
Derek Jonese701d762010-03-02 18:17:01 -0600339
340 /*
341 * Makes PHP tags safe
342 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400343 * Note: XML tags are inadvertently replaced too:
Derek Jonese701d762010-03-02 18:17:01 -0600344 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400345 * <?xml
Derek Jonese701d762010-03-02 18:17:01 -0600346 *
347 * But it doesn't seem to pose a problem.
Derek Jonese701d762010-03-02 18:17:01 -0600348 */
349 if ($is_image === TRUE)
350 {
David Behler07b53422011-08-15 00:25:06 +0200351 // Images have a tendency to have the PHP short opening and
352 // closing tags every so often so we skip those and only
Pascal Krietec9c045a2011-04-05 14:50:41 -0400353 // do the long opening tags.
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200354 $str = preg_replace('/<\?(php)/i', '&lt;?\\1', $str);
Derek Jonese701d762010-03-02 18:17:01 -0600355 }
356 else
357 {
Derek Jones37f4b9c2011-07-01 17:56:50 -0500358 $str = str_replace(array('<?', '?'.'>'), array('&lt;?', '?&gt;'), $str);
Derek Jonese701d762010-03-02 18:17:01 -0600359 }
Barry Mienydd671972010-10-04 16:33:58 +0200360
Derek Jonese701d762010-03-02 18:17:01 -0600361 /*
362 * Compact any exploded words
363 *
Derek Jones37f4b9c2011-07-01 17:56:50 -0500364 * This corrects words like: j a v a s c r i p t
Derek Jonese701d762010-03-02 18:17:01 -0600365 * These words are compacted back to their correct state.
Derek Jonese701d762010-03-02 18:17:01 -0600366 */
Pascal Krietec9c045a2011-04-05 14:50:41 -0400367 $words = array(
Timothy Warren40403d22012-04-19 16:38:50 -0400368 'javascript', 'expression', 'vbscript', 'script',
369 'applet', 'alert', 'document', 'write', 'cookie', 'window'
370 );
David Behler07b53422011-08-15 00:25:06 +0200371
Derek Jonese701d762010-03-02 18:17:01 -0600372 foreach ($words as $word)
373 {
Andrey Andreev67ccdc02012-02-27 23:57:58 +0200374 $word = implode('\s*', str_split($word)).'\s*';
Derek Jonese701d762010-03-02 18:17:01 -0600375
376 // We only want to do this when it is followed by a non-word character
377 // That way valid stuff like "dealer to" does not become "dealerto"
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300378 $str = preg_replace_callback('#('.substr($word, 0, -3).')(\W)#is', array($this, '_compact_exploded_words'), $str);
Derek Jonese701d762010-03-02 18:17:01 -0600379 }
Barry Mienydd671972010-10-04 16:33:58 +0200380
Derek Jonese701d762010-03-02 18:17:01 -0600381 /*
382 * Remove disallowed Javascript in links or img tags
David Behler07b53422011-08-15 00:25:06 +0200383 * We used to do some version comparisons and use of stripos for PHP5,
384 * but it is dog slow compared to these simplified non-capturing
Pascal Krietec9c045a2011-04-05 14:50:41 -0400385 * preg_match(), especially if the pattern exists in the string
Derek Jonese701d762010-03-02 18:17:01 -0600386 */
387 do
388 {
389 $original = $str;
Barry Mienydd671972010-10-04 16:33:58 +0200390
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200391 if (preg_match('/<a/i', $str))
Derek Jonese701d762010-03-02 18:17:01 -0600392 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200393 $str = preg_replace_callback('#<a\s+([^>]*?)(>|$)#si', array($this, '_js_link_removal'), $str);
Derek Jonese701d762010-03-02 18:17:01 -0600394 }
Barry Mienydd671972010-10-04 16:33:58 +0200395
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200396 if (preg_match('/<img/i', $str))
Derek Jonese701d762010-03-02 18:17:01 -0600397 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200398 $str = preg_replace_callback('#<img\s+([^>]*?)(\s?/?>|$)#si', array($this, '_js_img_removal'), $str);
Derek Jonese701d762010-03-02 18:17:01 -0600399 }
Barry Mienydd671972010-10-04 16:33:58 +0200400
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200401 if (preg_match('/(script|xss)/i', $str))
Derek Jonese701d762010-03-02 18:17:01 -0600402 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200403 $str = preg_replace('#<(/*)(script|xss)(.*?)\>#si', '[removed]', $str);
Derek Jonese701d762010-03-02 18:17:01 -0600404 }
405 }
Pascal Krietec9c045a2011-04-05 14:50:41 -0400406 while($original != $str);
Derek Jonese701d762010-03-02 18:17:01 -0600407
408 unset($original);
409
Pascal Krietec9c045a2011-04-05 14:50:41 -0400410 // Remove evil attributes such as style, onclick and xmlns
411 $str = $this->_remove_evil_attributes($str, $is_image);
Barry Mienydd671972010-10-04 16:33:58 +0200412
Derek Jonese701d762010-03-02 18:17:01 -0600413 /*
414 * Sanitize naughty HTML elements
415 *
416 * If a tag containing any of the words in the list
417 * below is found, the tag gets converted to entities.
418 *
419 * So this: <blink>
420 * Becomes: &lt;blink&gt;
Derek Jonese701d762010-03-02 18:17:01 -0600421 */
422 $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';
423 $str = preg_replace_callback('#<(/*\s*)('.$naughty.')([^><]*)([><]*)#is', array($this, '_sanitize_naughty_html'), $str);
424
425 /*
426 * Sanitize naughty scripting elements
427 *
428 * Similar to above, only instead of looking for
429 * tags it looks for PHP and JavaScript commands
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200430 * that are disallowed. Rather than removing the
Derek Jonese701d762010-03-02 18:17:01 -0600431 * code, it simply converts the parenthesis to entities
432 * rendering the code un-executable.
433 *
434 * For example: eval('some code')
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200435 * Becomes: eval&#40;'some code'&#41;
Derek Jonese701d762010-03-02 18:17:01 -0600436 */
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200437 $str = preg_replace('#(alert|cmd|passthru|eval|exec|expression|system|fopen|fsockopen|file|file_get_contents|readfile|unlink)(\s*)\((.*?)\)#si',
438 '\\1\\2&#40;\\3&#41;',
439 $str);
Barry Mienydd671972010-10-04 16:33:58 +0200440
Pascal Krietec9c045a2011-04-05 14:50:41 -0400441 // Final clean up
442 // This adds a bit of extra precaution in case
443 // something got through the above filters
444 $str = $this->_do_never_allowed($str);
Derek Jonese701d762010-03-02 18:17:01 -0600445
446 /*
Pascal Krietec9c045a2011-04-05 14:50:41 -0400447 * Images are Handled in a Special Way
David Behler07b53422011-08-15 00:25:06 +0200448 * - Essentially, we want to know that after all of the character
449 * conversion is done whether any unwanted, likely XSS, code was found.
Pascal Krietec9c045a2011-04-05 14:50:41 -0400450 * If not, we return TRUE, as the image is clean.
David Behler07b53422011-08-15 00:25:06 +0200451 * However, if the string post-conversion does not matched the
452 * string post-removal of XSS, then it fails, as there was unwanted XSS
Pascal Krietec9c045a2011-04-05 14:50:41 -0400453 * code found and removed/changed during processing.
Derek Jonese701d762010-03-02 18:17:01 -0600454 */
Derek Jonese701d762010-03-02 18:17:01 -0600455 if ($is_image === TRUE)
456 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200457 return ($str === $converted_string);
Derek Jonese701d762010-03-02 18:17:01 -0600458 }
Barry Mienydd671972010-10-04 16:33:58 +0200459
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200460 log_message('debug', 'XSS Filtering completed');
Derek Jonese701d762010-03-02 18:17:01 -0600461 return $str;
462 }
463
464 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200465
Derek Jonese701d762010-03-02 18:17:01 -0600466 /**
467 * Random Hash for protecting URLs
468 *
Derek Jonese701d762010-03-02 18:17:01 -0600469 * @return string
470 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500471 public function xss_hash()
Barry Mienydd671972010-10-04 16:33:58 +0200472 {
Pascal Krietec9c045a2011-04-05 14:50:41 -0400473 if ($this->_xss_hash == '')
Derek Jonese701d762010-03-02 18:17:01 -0600474 {
Pascal Krietec38e3b62011-11-14 13:55:00 -0500475 mt_srand();
Pascal Krietec9c045a2011-04-05 14:50:41 -0400476 $this->_xss_hash = md5(time() + mt_rand(0, 1999999999));
Derek Jonese701d762010-03-02 18:17:01 -0600477 }
478
Pascal Krietec9c045a2011-04-05 14:50:41 -0400479 return $this->_xss_hash;
Derek Jonese701d762010-03-02 18:17:01 -0600480 }
481
482 // --------------------------------------------------------------------
483
484 /**
Derek Jonesa0911472010-03-30 10:33:09 -0500485 * HTML Entities Decode
486 *
487 * This function is a replacement for html_entity_decode()
488 *
Pascal Krietec38e3b62011-11-14 13:55:00 -0500489 * The reason we are not using html_entity_decode() by itself is because
490 * while it is not technically correct to leave out the semicolon
491 * at the end of an entity most browsers will still interpret the entity
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200492 * correctly. html_entity_decode() does not convert entities without
Pascal Krietec38e3b62011-11-14 13:55:00 -0500493 * semicolons, so we are left with our own little solution here. Bummer.
Derek Jonesa0911472010-03-30 10:33:09 -0500494 *
Derek Jonesa0911472010-03-30 10:33:09 -0500495 * @param string
496 * @param string
497 * @return string
498 */
freewil8cc0cfe2011-08-27 21:53:00 -0400499 public function entity_decode($str, $charset = NULL)
Derek Jonesa0911472010-03-30 10:33:09 -0500500 {
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300501 if (strpos($str, '&') === FALSE)
freewil5c9b0d12011-08-28 12:15:23 -0400502 {
503 return $str;
504 }
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300505
freewil5c9b0d12011-08-28 12:15:23 -0400506 if (empty($charset))
507 {
508 $charset = config_item('charset');
509 }
Barry Mienydd671972010-10-04 16:33:58 +0200510
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300511 $str = html_entity_decode($str, ENT_COMPAT, $charset);
512 $str = preg_replace('~&#x(0*[0-9a-f]{2,5})~ei', 'chr(hexdec("\\1"))', $str);
513 return preg_replace('~&#([0-9]{2,4})~e', 'chr(\\1)', $str);
Derek Jonesa0911472010-03-30 10:33:09 -0500514 }
Barry Mienydd671972010-10-04 16:33:58 +0200515
Derek Jonesa0911472010-03-30 10:33:09 -0500516 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200517
Derek Jonesa0911472010-03-30 10:33:09 -0500518 /**
Derek Jonese701d762010-03-02 18:17:01 -0600519 * Filename Security
520 *
Derek Jonese701d762010-03-02 18:17:01 -0600521 * @param string
David Behler07b53422011-08-15 00:25:06 +0200522 * @param bool
Derek Jonese701d762010-03-02 18:17:01 -0600523 * @return string
524 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500525 public function sanitize_filename($str, $relative_path = FALSE)
Derek Jonese701d762010-03-02 18:17:01 -0600526 {
527 $bad = array(
Timothy Warren40403d22012-04-19 16:38:50 -0400528 '../', '<!--', '-->', '<', '>',
529 "'", '"', '&', '$', '#',
530 '{', '}', '[', ']', '=',
531 ';', '?', '%20', '%22',
532 '%3c', // <
533 '%253c', // <
534 '%3e', // >
535 '%0e', // >
536 '%28', // (
537 '%29', // )
538 '%2528', // (
539 '%26', // &
540 '%24', // $
541 '%3f', // ?
542 '%3b', // ;
543 '%3d' // =
544 );
David Behler07b53422011-08-15 00:25:06 +0200545
Derek Jones2ef37592010-10-06 17:51:59 -0500546 if ( ! $relative_path)
547 {
548 $bad[] = './';
549 $bad[] = '/';
550 }
Derek Jonese701d762010-03-02 18:17:01 -0600551
Pascal Krietec9c045a2011-04-05 14:50:41 -0400552 $str = remove_invisible_characters($str, FALSE);
Derek Jonese701d762010-03-02 18:17:01 -0600553 return stripslashes(str_replace($bad, '', $str));
554 }
555
Pascal Krietec9c045a2011-04-05 14:50:41 -0400556 // ----------------------------------------------------------------
557
558 /**
559 * Compact Exploded Words
560 *
561 * Callback function for xss_clean() to remove whitespace from
562 * things like j a v a s c r i p t
563 *
Timothy Warrenad475052012-04-19 13:21:06 -0400564 * @param array
565 * @return string
Pascal Krietec9c045a2011-04-05 14:50:41 -0400566 */
567 protected function _compact_exploded_words($matches)
568 {
569 return preg_replace('/\s+/s', '', $matches[1]).$matches[2];
570 }
571
572 // --------------------------------------------------------------------
David Behler07b53422011-08-15 00:25:06 +0200573
Timothy Warrenad475052012-04-19 13:21:06 -0400574 /**
575 * Remove Evil HTML Attributes (like event handlers and style)
Pascal Krietec9c045a2011-04-05 14:50:41 -0400576 *
577 * It removes the evil attribute and either:
578 * - Everything up until a space
579 * For example, everything between the pipes:
580 * <a |style=document.write('hello');alert('world');| class=link>
David Behler07b53422011-08-15 00:25:06 +0200581 * - Everything inside the quotes
Pascal Krietec9c045a2011-04-05 14:50:41 -0400582 * For example, everything between the pipes:
583 * <a |style="document.write('hello'); alert('world');"| class="link">
584 *
585 * @param string $str The string to check
586 * @param boolean $is_image TRUE if this is an image
587 * @return string The string with the evil attributes removed
588 */
589 protected function _remove_evil_attributes($str, $is_image)
590 {
591 // All javascript event handlers (e.g. onload, onclick, onmouseover), style, and xmlns
Pascal Krietec38e3b62011-11-14 13:55:00 -0500592 $evil_attributes = array('on\w*', 'style', 'xmlns', 'formaction');
Pascal Krietec9c045a2011-04-05 14:50:41 -0400593
594 if ($is_image === TRUE)
595 {
596 /*
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200597 * Adobe Photoshop puts XML metadata into JFIF images,
Pascal Krietec9c045a2011-04-05 14:50:41 -0400598 * including namespacing, so we have to allow this for images.
599 */
600 unset($evil_attributes[array_search('xmlns', $evil_attributes)]);
601 }
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200602
Pascal Krietec9c045a2011-04-05 14:50:41 -0400603 do {
Pascal Krietec38e3b62011-11-14 13:55:00 -0500604 $count = 0;
605 $attribs = array();
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200606
Pascal Krietec38e3b62011-11-14 13:55:00 -0500607 // find occurrences of illegal attribute strings without quotes
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200608 preg_match_all('/('.implode('|', $evil_attributes).')\s*=\s*([^\s]*)/is', $str, $matches, PREG_SET_ORDER);
609
Pascal Krietec38e3b62011-11-14 13:55:00 -0500610 foreach ($matches as $attr)
611 {
612 $attribs[] = preg_quote($attr[0], '/');
613 }
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200614
Pascal Krietec38e3b62011-11-14 13:55:00 -0500615 // find occurrences of illegal attribute strings with quotes (042 and 047 are octal quotes)
Andrey Andreev67ccdc02012-02-27 23:57:58 +0200616 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 +0200617
Pascal Krietec38e3b62011-11-14 13:55:00 -0500618 foreach ($matches as $attr)
619 {
620 $attribs[] = preg_quote($attr[0], '/');
621 }
622
623 // replace illegal attribute strings that are inside an html tag
624 if (count($attribs) > 0)
625 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200626 $str = preg_replace('/<(\/?[^><]+?)([^A-Za-z\-])('.implode('|', $attribs).')([\s><])([><]*)/i', '<$1$2$4$5', $str, -1, $count);
Pascal Krietec38e3b62011-11-14 13:55:00 -0500627 }
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200628
Pascal Krietec38e3b62011-11-14 13:55:00 -0500629 } while ($count);
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200630
Pascal Krietec9c045a2011-04-05 14:50:41 -0400631 return $str;
632 }
David Behler07b53422011-08-15 00:25:06 +0200633
Pascal Krietec9c045a2011-04-05 14:50:41 -0400634 // --------------------------------------------------------------------
635
636 /**
637 * Sanitize Naughty HTML
638 *
639 * Callback function for xss_clean() to remove naughty HTML elements
640 *
641 * @param array
642 * @return string
643 */
644 protected function _sanitize_naughty_html($matches)
645 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200646 return '&lt;'.$matches[1].$matches[2].$matches[3] // encode opening brace
647 // encode captured opening or closing brace to prevent recursive vectors:
Andrey Andreev67ccdc02012-02-27 23:57:58 +0200648 .str_replace(array('>', '<'), array('&gt;', '&lt;'), $matches[4]);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400649 }
650
651 // --------------------------------------------------------------------
652
653 /**
654 * JS Link Removal
655 *
656 * Callback function for xss_clean() to sanitize links
657 * This limits the PCRE backtracks, making it more performance friendly
658 * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in
659 * PHP 5.2+ on link-heavy strings
660 *
661 * @param array
662 * @return string
663 */
664 protected function _js_link_removal($match)
665 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200666 return str_replace($match[1],
667 preg_replace('#href=.*?(alert\(|alert&\#40;|javascript\:|livescript\:|mocha\:|charset\=|window\.|document\.|\.cookie|<script|<xss|base64\s*,)#si',
668 '',
669 $this->_filter_attributes(str_replace(array('<', '>'), '', $match[1]))
670 ),
671 $match[0]);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400672 }
673
674 // --------------------------------------------------------------------
675
676 /**
677 * JS Image Removal
678 *
679 * Callback function for xss_clean() to sanitize image tags
680 * This limits the PCRE backtracks, making it more performance friendly
681 * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in
682 * PHP 5.2+ on image tag heavy strings
683 *
684 * @param array
685 * @return string
686 */
687 protected function _js_img_removal($match)
688 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200689 return str_replace($match[1],
690 preg_replace('#src=.*?(alert\(|alert&\#40;|javascript\:|livescript\:|mocha\:|charset\=|window\.|document\.|\.cookie|<script|<xss|base64\s*,)#si',
691 '',
692 $this->_filter_attributes(str_replace(array('<', '>'), '', $match[1]))
693 ),
694 $match[0]);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400695 }
696
697 // --------------------------------------------------------------------
698
699 /**
700 * Attribute Conversion
701 *
702 * Used as a callback for XSS Clean
703 *
704 * @param array
705 * @return string
706 */
707 protected function _convert_attribute($match)
708 {
709 return str_replace(array('>', '<', '\\'), array('&gt;', '&lt;', '\\\\'), $match[0]);
710 }
711
712 // --------------------------------------------------------------------
713
714 /**
715 * Filter Attributes
716 *
717 * Filters tag attributes for consistency and safety
718 *
719 * @param string
720 * @return string
721 */
722 protected function _filter_attributes($str)
723 {
724 $out = '';
Pascal Krietec9c045a2011-04-05 14:50:41 -0400725 if (preg_match_all('#\s*[a-z\-]+\s*=\s*(\042|\047)([^\\1]*?)\\1#is', $str, $matches))
726 {
727 foreach ($matches[0] as $match)
728 {
Andrey Andreev4562f2c2012-01-09 23:39:50 +0200729 $out .= preg_replace('#/\*.*?\*/#s', '', $match);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400730 }
731 }
732
733 return $out;
734 }
735
736 // --------------------------------------------------------------------
737
738 /**
739 * HTML Entity Decode Callback
740 *
741 * Used as a callback for XSS Clean
742 *
743 * @param array
744 * @return string
745 */
746 protected function _decode_entity($match)
747 {
748 return $this->entity_decode($match[0], strtoupper(config_item('charset')));
749 }
750
751 // --------------------------------------------------------------------
David Behler07b53422011-08-15 00:25:06 +0200752
Pascal Krietec9c045a2011-04-05 14:50:41 -0400753 /**
754 * Validate URL entities
755 *
756 * Called by xss_clean()
757 *
David Behler07b53422011-08-15 00:25:06 +0200758 * @param string
Pascal Krietec9c045a2011-04-05 14:50:41 -0400759 * @return string
760 */
761 protected function _validate_entities($str)
762 {
763 /*
764 * Protect GET variables in URLs
765 */
David Behler07b53422011-08-15 00:25:06 +0200766
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200767 // 901119URL5918AMP18930PROTECT8198
768 $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 -0400769
770 /*
771 * Validate standard character entities
772 *
Derek Jones37f4b9c2011-07-01 17:56:50 -0500773 * Add a semicolon if missing. We do this to enable
Pascal Krietec9c045a2011-04-05 14:50:41 -0400774 * the conversion of entities to ASCII later.
Pascal Krietec9c045a2011-04-05 14:50:41 -0400775 */
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200776 $str = preg_replace('#(&\#?[0-9a-z]{2,})([\x00-\x20])*;?#i', '\\1;\\2', $str);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400777
778 /*
779 * Validate UTF16 two byte encoding (x00)
780 *
781 * Just as above, adds a semicolon if missing.
Pascal Krietec9c045a2011-04-05 14:50:41 -0400782 */
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200783 $str = preg_replace('#(&\#x?)([0-9A-F]+);?#i', '\\1\\2;', $str);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400784
785 /*
786 * Un-Protect GET variables in URLs
787 */
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200788 return str_replace($this->xss_hash(), '&', $str);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400789 }
790
791 // ----------------------------------------------------------------------
792
793 /**
794 * Do Never Allowed
795 *
796 * A utility function for xss_clean()
797 *
798 * @param string
799 * @return string
800 */
801 protected function _do_never_allowed($str)
802 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200803 $str = str_replace(array_keys($this->_never_allowed_str), $this->_never_allowed_str, $str);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400804
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200805 foreach ($this->_never_allowed_regex as $regex)
Pascal Krietec9c045a2011-04-05 14:50:41 -0400806 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200807 $str = preg_replace('#'.$regex.'#i', '[removed]', $str);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400808 }
David Behler07b53422011-08-15 00:25:06 +0200809
Pascal Krietec9c045a2011-04-05 14:50:41 -0400810 return $str;
811 }
812
813 // --------------------------------------------------------------------
814
815 /**
816 * Set Cross Site Request Forgery Protection Cookie
817 *
818 * @return string
819 */
820 protected function _csrf_set_hash()
821 {
822 if ($this->_csrf_hash == '')
823 {
David Behler07b53422011-08-15 00:25:06 +0200824 // If the cookie exists we will use it's value.
Pascal Krietec9c045a2011-04-05 14:50:41 -0400825 // We don't necessarily want to regenerate it with
David Behler07b53422011-08-15 00:25:06 +0200826 // each page load since a page could contain embedded
Pascal Krietec9c045a2011-04-05 14:50:41 -0400827 // sub-pages causing this feature to fail
David Behler07b53422011-08-15 00:25:06 +0200828 if (isset($_COOKIE[$this->_csrf_cookie_name]) &&
Pascal Krietec9c045a2011-04-05 14:50:41 -0400829 $_COOKIE[$this->_csrf_cookie_name] != '')
830 {
831 return $this->_csrf_hash = $_COOKIE[$this->_csrf_cookie_name];
832 }
David Behler07b53422011-08-15 00:25:06 +0200833
Chris Berthed93e6f32011-09-25 10:33:25 -0400834 $this->_csrf_hash = md5(uniqid(rand(), TRUE));
835 $this->csrf_set_cookie();
Pascal Krietec9c045a2011-04-05 14:50:41 -0400836 }
837
838 return $this->_csrf_hash;
839 }
840
Derek Jonese701d762010-03-02 18:17:01 -0600841}
Derek Jonese701d762010-03-02 18:17:01 -0600842
843/* End of file Security.php */
Timothy Warren40403d22012-04-19 16:38:50 -0400844/* Location: ./system/core/Security.php */