blob: a4d8c95ef812fbe022fcdc8c988465f734e6e265 [file] [log] [blame]
Andrey Andreevc5536aa2012-11-01 17:33:58 +02001<?php
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
darwinel871754a2014-02-11 17:34:57 +010021 * @copyright Copyright (c) 2008 - 2014, 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 */
Andrey Andreevc5536aa2012-11-01 17:33:58 +020027defined('BASEPATH') OR exit('No direct script access allowed');
Derek Jonese701d762010-03-02 18:17:01 -060028
Derek Jonese701d762010-03-02 18:17:01 -060029/**
30 * Security Class
31 *
32 * @package CodeIgniter
33 * @subpackage Libraries
34 * @category Security
Derek Jonesf4a4bd82011-10-20 12:18:42 -050035 * @author EllisLab Dev Team
Pascal Krietec9c045a2011-04-05 14:50:41 -040036 * @link http://codeigniter.com/user_guide/libraries/security.html
Derek Jonese701d762010-03-02 18:17:01 -060037 */
38class CI_Security {
Barry Mienydd671972010-10-04 16:33:58 +020039
David Behler07b53422011-08-15 00:25:06 +020040 /**
Hunter Wua8d6d3b2013-08-03 23:17:45 +080041 * List of sanitize filename strings
42 *
43 * @var array
44 */
Hunter Wu4495cc72013-08-04 12:31:52 +080045 public $filename_bad_chars = array(
Hunter Wua8d6d3b2013-08-03 23:17:45 +080046 '../', '<!--', '-->', '<', '>',
47 "'", '"', '&', '$', '#',
48 '{', '}', '[', ']', '=',
49 ';', '?', '%20', '%22',
50 '%3c', // <
51 '%253c', // <
52 '%3e', // >
53 '%0e', // >
54 '%28', // (
55 '%29', // )
56 '%2528', // (
57 '%26', // &
58 '%24', // $
59 '%3f', // ?
60 '%3b', // ;
61 '%3d' // =
62 );
63
64 /**
Andrey Andreevc67c3fb2014-01-22 13:26:00 +020065 * HTML5 entities
66 *
67 * @var array
68 */
69 public $html5_entities = array(
70 '&colon;' => ':',
71 '&lpar;' => '(',
Andrey Andreevd98cbb82014-01-24 18:34:27 +020072 '&rpar;' => ')',
Andrey Andreevee7633c2014-01-24 18:47:20 +020073 '&newline;' => "\n",
74 '&tab;' => "\t"
Andrey Andreevc67c3fb2014-01-22 13:26:00 +020075 );
76
77 /**
Andrey Andreev64354102012-10-28 14:16:02 +020078 * XSS Hash
David Behler07b53422011-08-15 00:25:06 +020079 *
Andrey Andreev64354102012-10-28 14:16:02 +020080 * Random Hash for protecting URLs.
81 *
82 * @var string
David Behler07b53422011-08-15 00:25:06 +020083 */
Timothy Warren48a7fbb2012-04-23 11:58:16 -040084 protected $_xss_hash = '';
Andrey Andreev3d113bd2011-10-05 00:03:20 +030085
David Behler07b53422011-08-15 00:25:06 +020086 /**
Andrey Andreev64354102012-10-28 14:16:02 +020087 * CSRF Hash
David Behler07b53422011-08-15 00:25:06 +020088 *
Andrey Andreev64354102012-10-28 14:16:02 +020089 * Random hash for Cross Site Request Forgery protection cookie
90 *
91 * @var string
David Behler07b53422011-08-15 00:25:06 +020092 */
Timothy Warren48a7fbb2012-04-23 11:58:16 -040093 protected $_csrf_hash = '';
Andrey Andreev3d113bd2011-10-05 00:03:20 +030094
David Behler07b53422011-08-15 00:25:06 +020095 /**
Andrey Andreev64354102012-10-28 14:16:02 +020096 * CSRF Expire time
David Behler07b53422011-08-15 00:25:06 +020097 *
Andrey Andreev64354102012-10-28 14:16:02 +020098 * Expiration time for Cross Site Request Forgery protection cookie.
99 * Defaults to two hours (in seconds).
100 *
101 * @var int
David Behler07b53422011-08-15 00:25:06 +0200102 */
Timothy Warren48a7fbb2012-04-23 11:58:16 -0400103 protected $_csrf_expire = 7200;
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300104
David Behler07b53422011-08-15 00:25:06 +0200105 /**
Andrey Andreev64354102012-10-28 14:16:02 +0200106 * CSRF Token name
David Behler07b53422011-08-15 00:25:06 +0200107 *
Andrey Andreev64354102012-10-28 14:16:02 +0200108 * Token name for Cross Site Request Forgery protection cookie.
109 *
110 * @var string
David Behler07b53422011-08-15 00:25:06 +0200111 */
Timothy Warren48a7fbb2012-04-23 11:58:16 -0400112 protected $_csrf_token_name = 'ci_csrf_token';
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300113
David Behler07b53422011-08-15 00:25:06 +0200114 /**
Andrey Andreev64354102012-10-28 14:16:02 +0200115 * CSRF Cookie name
David Behler07b53422011-08-15 00:25:06 +0200116 *
Andrey Andreev64354102012-10-28 14:16:02 +0200117 * Cookie name for Cross Site Request Forgery protection cookie.
118 *
119 * @var string
David Behler07b53422011-08-15 00:25:06 +0200120 */
Timothy Warren48a7fbb2012-04-23 11:58:16 -0400121 protected $_csrf_cookie_name = 'ci_csrf_token';
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300122
David Behler07b53422011-08-15 00:25:06 +0200123 /**
124 * List of never allowed strings
125 *
Andrey Andreev64354102012-10-28 14:16:02 +0200126 * @var array
David Behler07b53422011-08-15 00:25:06 +0200127 */
Timothy Warren48a7fbb2012-04-23 11:58:16 -0400128 protected $_never_allowed_str = array(
Timothy Warren40403d22012-04-19 16:38:50 -0400129 'document.cookie' => '[removed]',
130 'document.write' => '[removed]',
131 '.parentNode' => '[removed]',
132 '.innerHTML' => '[removed]',
Timothy Warren40403d22012-04-19 16:38:50 -0400133 '-moz-binding' => '[removed]',
134 '<!--' => '&lt;!--',
135 '-->' => '--&gt;',
136 '<![CDATA[' => '&lt;![CDATA[',
137 '<comment>' => '&lt;comment&gt;'
138 );
Derek Jonese701d762010-03-02 18:17:01 -0600139
David Behler07b53422011-08-15 00:25:06 +0200140 /**
Andrey Andreev64354102012-10-28 14:16:02 +0200141 * List of never allowed regex replacements
David Behler07b53422011-08-15 00:25:06 +0200142 *
Andrey Andreev64354102012-10-28 14:16:02 +0200143 * @var array
David Behler07b53422011-08-15 00:25:06 +0200144 */
Pascal Krietec9c045a2011-04-05 14:50:41 -0400145 protected $_never_allowed_regex = array(
Timothy Warren40403d22012-04-19 16:38:50 -0400146 'javascript\s*:',
Andrey Andreev1bbc5642014-01-07 12:45:27 +0200147 '(document|(document\.)?window)\.(location|on\w*)',
Timothy Warren40403d22012-04-19 16:38:50 -0400148 'expression\s*(\(|&\#40;)', // CSS and IE
149 'vbscript\s*:', // IE, surprise!
Andrey Andreeva30a7172014-02-10 09:17:25 +0200150 'wscript\s*:', // IE
Andrey Andreevf7f9dca2014-02-10 12:41:00 +0200151 'jscript\s*:', // IE
Andrey Andreeva30a7172014-02-10 09:17:25 +0200152 'vbs\s*:', // IE
Andrey Andreev43568062014-01-21 23:52:31 +0200153 'Redirect\s+30\d',
Wes Bakerd3481352012-05-07 16:49:33 -0400154 "([\"'])?data\s*:[^\\1]*?base64[^\\1]*?,[^\\1]*?\\1?"
Timothy Warren40403d22012-04-19 16:38:50 -0400155 );
Andrey Andreev92ebfb62012-05-17 12:49:24 +0300156
Timothy Warrenad475052012-04-19 13:21:06 -0400157 /**
Andrey Andreev64354102012-10-28 14:16:02 +0200158 * Class constructor
Andrey Andreev92ebfb62012-05-17 12:49:24 +0300159 *
160 * @return void
Timothy Warrenad475052012-04-19 13:21:06 -0400161 */
Greg Akera9263282010-11-10 15:26:43 -0600162 public function __construct()
Derek Jonese701d762010-03-02 18:17:01 -0600163 {
Andrey Andreev67ccdc02012-02-27 23:57:58 +0200164 // Is CSRF protection enabled?
165 if (config_item('csrf_protection') === TRUE)
patworkef1a55a2011-04-09 13:04:06 +0200166 {
Andrey Andreev67ccdc02012-02-27 23:57:58 +0200167 // CSRF config
168 foreach (array('csrf_expire', 'csrf_token_name', 'csrf_cookie_name') as $key)
patworkef1a55a2011-04-09 13:04:06 +0200169 {
Andrey Andreev67ccdc02012-02-27 23:57:58 +0200170 if (FALSE !== ($val = config_item($key)))
171 {
172 $this->{'_'.$key} = $val;
173 }
patworkef1a55a2011-04-09 13:04:06 +0200174 }
patworkef1a55a2011-04-09 13:04:06 +0200175
Andrey Andreev67ccdc02012-02-27 23:57:58 +0200176 // Append application specific cookie prefix
177 if (config_item('cookie_prefix'))
178 {
179 $this->_csrf_cookie_name = config_item('cookie_prefix').$this->_csrf_cookie_name;
180 }
Derek Jonesb3f10a22010-07-25 19:11:26 -0500181
Andrey Andreev67ccdc02012-02-27 23:57:58 +0200182 // Set the CSRF hash
183 $this->_csrf_set_hash();
184 }
Derek Allard958543a2010-07-22 14:10:26 -0400185
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200186 log_message('debug', 'Security Class Initialized');
Derek Jonese701d762010-03-02 18:17:01 -0600187 }
188
189 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200190
Derek Jonese701d762010-03-02 18:17:01 -0600191 /**
Andrey Andreev64354102012-10-28 14:16:02 +0200192 * CSRF Verify
Derek Jonese701d762010-03-02 18:17:01 -0600193 *
Andrew Podner4296a652012-12-17 07:51:15 -0500194 * @return CI_Security
Derek Jonese701d762010-03-02 18:17:01 -0600195 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500196 public function csrf_verify()
Derek Allard958543a2010-07-22 14:10:26 -0400197 {
Andrey Andreev5d27c432012-03-08 12:01:52 +0200198 // If it's not a POST request we will set the CSRF cookie
199 if (strtoupper($_SERVER['REQUEST_METHOD']) !== 'POST')
Derek Jonese701d762010-03-02 18:17:01 -0600200 {
201 return $this->csrf_set_cookie();
202 }
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300203
Alex Bilbieaeb2c3e2011-08-21 16:14:54 +0100204 // Check if URI has been whitelisted from CSRF checks
205 if ($exclude_uris = config_item('csrf_exclude_uris'))
206 {
207 $uri = load_class('URI', 'core');
208 if (in_array($uri->uri_string(), $exclude_uris))
209 {
210 return $this;
211 }
212 }
Derek Jonese701d762010-03-02 18:17:01 -0600213
214 // Do the tokens exist in both the _POST and _COOKIE arrays?
Andrey Andreevf795ab52012-10-24 21:28:25 +0300215 if ( ! isset($_POST[$this->_csrf_token_name], $_COOKIE[$this->_csrf_cookie_name])
Alex Bilbieed944a32012-06-02 11:07:47 +0100216 OR $_POST[$this->_csrf_token_name] !== $_COOKIE[$this->_csrf_cookie_name]) // Do the tokens match?
Derek Jonese701d762010-03-02 18:17:01 -0600217 {
218 $this->csrf_show_error();
219 }
220
Andrey Andreev4562f2c2012-01-09 23:39:50 +0200221 // We kill this since we're done and we don't want to polute the _POST array
Pascal Krietec9c045a2011-04-05 14:50:41 -0400222 unset($_POST[$this->_csrf_token_name]);
Barry Mienydd671972010-10-04 16:33:58 +0200223
RS712be25a62011-12-31 16:02:04 -0200224 // Regenerate on every submission?
225 if (config_item('csrf_regenerate'))
226 {
227 // Nothing should last forever
228 unset($_COOKIE[$this->_csrf_cookie_name]);
229 $this->_csrf_hash = '';
230 }
Andrey Andreev8a7d0782012-01-08 05:43:42 +0200231
Derek Jonesb3f10a22010-07-25 19:11:26 -0500232 $this->_csrf_set_hash();
233 $this->csrf_set_cookie();
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300234
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200235 log_message('debug', 'CSRF token verified');
Pascal Krietec9c045a2011-04-05 14:50:41 -0400236 return $this;
Derek Jonese701d762010-03-02 18:17:01 -0600237 }
Barry Mienydd671972010-10-04 16:33:58 +0200238
Derek Jonese701d762010-03-02 18:17:01 -0600239 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200240
Derek Jonese701d762010-03-02 18:17:01 -0600241 /**
Andrey Andreev64354102012-10-28 14:16:02 +0200242 * CSRF Set Cookie
Derek Jonese701d762010-03-02 18:17:01 -0600243 *
Taufan Aditya6c7526c2012-05-27 13:51:27 +0700244 * @codeCoverageIgnore
Andrew Podner4296a652012-12-17 07:51:15 -0500245 * @return CI_Security
Derek Jonese701d762010-03-02 18:17:01 -0600246 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500247 public function csrf_set_cookie()
Derek Jonese701d762010-03-02 18:17:01 -0600248 {
Pascal Krietec9c045a2011-04-05 14:50:41 -0400249 $expire = time() + $this->_csrf_expire;
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300250 $secure_cookie = (bool) config_item('cookie_secure');
Derek Jonese701d762010-03-02 18:17:01 -0600251
Andrey Andreev3fb02672012-10-22 16:48:01 +0300252 if ($secure_cookie && ! is_https())
Derek Jonese701d762010-03-02 18:17:01 -0600253 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200254 return FALSE;
Derek Jonese701d762010-03-02 18:17:01 -0600255 }
Derek Allard958543a2010-07-22 14:10:26 -0400256
freewil4ad0fd82012-03-13 22:37:42 -0400257 setcookie(
Andrey Andreev92ebfb62012-05-17 12:49:24 +0300258 $this->_csrf_cookie_name,
259 $this->_csrf_hash,
260 $expire,
261 config_item('cookie_path'),
262 config_item('cookie_domain'),
freewil4ad0fd82012-03-13 22:37:42 -0400263 $secure_cookie,
264 config_item('cookie_httponly')
265 );
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200266 log_message('debug', 'CRSF cookie Set');
David Behler07b53422011-08-15 00:25:06 +0200267
Pascal Krietec9c045a2011-04-05 14:50:41 -0400268 return $this;
Derek Jonese701d762010-03-02 18:17:01 -0600269 }
270
271 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200272
Derek Jonese701d762010-03-02 18:17:01 -0600273 /**
274 * Show CSRF Error
275 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400276 * @return void
Derek Jonese701d762010-03-02 18:17:01 -0600277 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500278 public function csrf_show_error()
Derek Jonese701d762010-03-02 18:17:01 -0600279 {
280 show_error('The action you have requested is not allowed.');
281 }
282
283 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200284
Derek Jonese701d762010-03-02 18:17:01 -0600285 /**
David Behler07b53422011-08-15 00:25:06 +0200286 * Get CSRF Hash
Pascal Krietec9c045a2011-04-05 14:50:41 -0400287 *
Andrey Andreev64354102012-10-28 14:16:02 +0200288 * @see CI_Security::$_csrf_hash
289 * @return string CSRF hash
Pascal Krietec9c045a2011-04-05 14:50:41 -0400290 */
291 public function get_csrf_hash()
292 {
293 return $this->_csrf_hash;
294 }
295
296 // --------------------------------------------------------------------
297
298 /**
299 * Get CSRF Token Name
300 *
Andrey Andreev64354102012-10-28 14:16:02 +0200301 * @see CI_Security::$_csrf_token_name
302 * @return string CSRF token name
Pascal Krietec9c045a2011-04-05 14:50:41 -0400303 */
304 public function get_csrf_token_name()
305 {
306 return $this->_csrf_token_name;
307 }
308
309 // --------------------------------------------------------------------
310
311 /**
Derek Jonese701d762010-03-02 18:17:01 -0600312 * XSS Clean
313 *
314 * Sanitizes data so that Cross Site Scripting Hacks can be
Andrey Andreev64354102012-10-28 14:16:02 +0200315 * prevented. This method does a fair amount of work but
Derek Jonese701d762010-03-02 18:17:01 -0600316 * it is extremely thorough, designed to prevent even the
Derek Jones37f4b9c2011-07-01 17:56:50 -0500317 * most obscure XSS attempts. Nothing is ever 100% foolproof,
Derek Jonese701d762010-03-02 18:17:01 -0600318 * of course, but I haven't been able to get anything passed
319 * the filter.
320 *
Andrey Andreev64354102012-10-28 14:16:02 +0200321 * Note: Should only be used to deal with data upon submission.
322 * It's not something that should be used for general
323 * runtime processing.
Derek Jonese701d762010-03-02 18:17:01 -0600324 *
Andrey Andreev64354102012-10-28 14:16:02 +0200325 * @link http://channel.bitflux.ch/wiki/XSS_Prevention
326 * Based in part on some code and ideas from Bitflux.
Derek Jonese701d762010-03-02 18:17:01 -0600327 *
Andrey Andreev64354102012-10-28 14:16:02 +0200328 * @link http://ha.ckers.org/xss.html
329 * To help develop this script I used this great list of
330 * vulnerabilities along with a few other hacks I've
331 * harvested from examining vulnerabilities in other programs.
Derek Jonese701d762010-03-02 18:17:01 -0600332 *
Andrey Andreev64354102012-10-28 14:16:02 +0200333 * @param string|string[] $str Input data
334 * @param bool $is_image Whether the input is an image
Derek Jonese701d762010-03-02 18:17:01 -0600335 * @return string
336 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500337 public function xss_clean($str, $is_image = FALSE)
Derek Jonese701d762010-03-02 18:17:01 -0600338 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200339 // Is the string an array?
Derek Jonese701d762010-03-02 18:17:01 -0600340 if (is_array($str))
341 {
342 while (list($key) = each($str))
343 {
344 $str[$key] = $this->xss_clean($str[$key]);
345 }
Barry Mienydd671972010-10-04 16:33:58 +0200346
Derek Jonese701d762010-03-02 18:17:01 -0600347 return $str;
348 }
349
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200350 // Remove Invisible Characters and validate entities in URLs
351 $str = $this->_validate_entities(remove_invisible_characters($str));
Derek Jonese701d762010-03-02 18:17:01 -0600352
353 /*
354 * URL Decode
355 *
356 * Just in case stuff like this is submitted:
357 *
358 * <a href="http://%77%77%77%2E%67%6F%6F%67%6C%65%2E%63%6F%6D">Google</a>
359 *
360 * Note: Use rawurldecode() so it does not remove plus signs
Derek Jonese701d762010-03-02 18:17:01 -0600361 */
Andrey Andreev29e12642014-02-10 13:24:44 +0200362 do
363 {
364 $str = rawurldecode($str);
365 }
366 while (preg_match('/%[0-9a-f]{2,}/i', $str));
Barry Mienydd671972010-10-04 16:33:58 +0200367
Derek Jonese701d762010-03-02 18:17:01 -0600368 /*
Barry Mienydd671972010-10-04 16:33:58 +0200369 * Convert character entities to ASCII
Derek Jonese701d762010-03-02 18:17:01 -0600370 *
371 * This permits our tests below to work reliably.
372 * We only convert entities that are within tags since
373 * these are the ones that will pose security problems.
Derek Jonese701d762010-03-02 18:17:01 -0600374 */
Derek Jonese701d762010-03-02 18:17:01 -0600375 $str = preg_replace_callback("/[a-z]+=([\'\"]).*?\\1/si", array($this, '_convert_attribute'), $str);
brian97807ccbe52012-12-11 20:24:12 +0200376 $str = preg_replace_callback('/<\w+.*/si', array($this, '_decode_entity'), $str);
Derek Jonese701d762010-03-02 18:17:01 -0600377
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200378 // Remove Invisible Characters Again!
Greg Aker757dda62010-04-14 19:06:19 -0500379 $str = remove_invisible_characters($str);
Barry Mienydd671972010-10-04 16:33:58 +0200380
Derek Jonese701d762010-03-02 18:17:01 -0600381 /*
382 * Convert all tabs to spaces
383 *
384 * This prevents strings like this: ja vascript
385 * NOTE: we deal with spaces between characters later.
David Behler07b53422011-08-15 00:25:06 +0200386 * NOTE: preg_replace was found to be amazingly slow here on
Pascal Krietec9c045a2011-04-05 14:50:41 -0400387 * large blocks of data, so we use str_replace.
Derek Jonese701d762010-03-02 18:17:01 -0600388 */
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200389 $str = str_replace("\t", ' ', $str);
Barry Mienydd671972010-10-04 16:33:58 +0200390
Andrey Andreev4562f2c2012-01-09 23:39:50 +0200391 // Capture converted string for later comparison
Derek Jonese701d762010-03-02 18:17:01 -0600392 $converted_string = $str;
Barry Mienydd671972010-10-04 16:33:58 +0200393
Pascal Krietec9c045a2011-04-05 14:50:41 -0400394 // Remove Strings that are never allowed
395 $str = $this->_do_never_allowed($str);
Derek Jonese701d762010-03-02 18:17:01 -0600396
397 /*
398 * Makes PHP tags safe
399 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400400 * Note: XML tags are inadvertently replaced too:
Derek Jonese701d762010-03-02 18:17:01 -0600401 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400402 * <?xml
Derek Jonese701d762010-03-02 18:17:01 -0600403 *
404 * But it doesn't seem to pose a problem.
Derek Jonese701d762010-03-02 18:17:01 -0600405 */
406 if ($is_image === TRUE)
407 {
David Behler07b53422011-08-15 00:25:06 +0200408 // Images have a tendency to have the PHP short opening and
409 // closing tags every so often so we skip those and only
Pascal Krietec9c045a2011-04-05 14:50:41 -0400410 // do the long opening tags.
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200411 $str = preg_replace('/<\?(php)/i', '&lt;?\\1', $str);
Derek Jonese701d762010-03-02 18:17:01 -0600412 }
413 else
414 {
Andrey Andreev838a9d62012-12-03 14:37:47 +0200415 $str = str_replace(array('<?', '?'.'>'), array('&lt;?', '?&gt;'), $str);
Derek Jonese701d762010-03-02 18:17:01 -0600416 }
Barry Mienydd671972010-10-04 16:33:58 +0200417
Derek Jonese701d762010-03-02 18:17:01 -0600418 /*
419 * Compact any exploded words
420 *
Derek Jones37f4b9c2011-07-01 17:56:50 -0500421 * This corrects words like: j a v a s c r i p t
Derek Jonese701d762010-03-02 18:17:01 -0600422 * These words are compacted back to their correct state.
Derek Jonese701d762010-03-02 18:17:01 -0600423 */
Pascal Krietec9c045a2011-04-05 14:50:41 -0400424 $words = array(
Andrey Andreeva30a7172014-02-10 09:17:25 +0200425 'javascript', 'expression', 'vbscript', 'jscript', 'wscript',
426 'vbs', 'script', 'base64', 'applet', 'alert', 'document',
427 'write', 'cookie', 'window', 'confirm', 'prompt'
Timothy Warren40403d22012-04-19 16:38:50 -0400428 );
David Behler07b53422011-08-15 00:25:06 +0200429
Derek Jonese701d762010-03-02 18:17:01 -0600430 foreach ($words as $word)
431 {
Andrey Andreev67ccdc02012-02-27 23:57:58 +0200432 $word = implode('\s*', str_split($word)).'\s*';
Derek Jonese701d762010-03-02 18:17:01 -0600433
434 // We only want to do this when it is followed by a non-word character
435 // That way valid stuff like "dealer to" does not become "dealerto"
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300436 $str = preg_replace_callback('#('.substr($word, 0, -3).')(\W)#is', array($this, '_compact_exploded_words'), $str);
Derek Jonese701d762010-03-02 18:17:01 -0600437 }
Barry Mienydd671972010-10-04 16:33:58 +0200438
Derek Jonese701d762010-03-02 18:17:01 -0600439 /*
440 * Remove disallowed Javascript in links or img tags
David Behler07b53422011-08-15 00:25:06 +0200441 * We used to do some version comparisons and use of stripos for PHP5,
442 * but it is dog slow compared to these simplified non-capturing
Pascal Krietec9c045a2011-04-05 14:50:41 -0400443 * preg_match(), especially if the pattern exists in the string
Andrey Andreev12445ca2014-01-25 01:55:52 +0200444 *
445 * Note: It was reported that not only space characters, but all in
446 * the following pattern can be parsed as separators between a tag name
447 * and its attributes: [\d\s"\'`;,\/\=\(\x00\x0B\x09\x0C]
448 * ... however, remove_invisible_characters() above already strips the
449 * hex-encoded ones, so we'll skip them below.
Derek Jonese701d762010-03-02 18:17:01 -0600450 */
451 do
452 {
453 $original = $str;
Barry Mienydd671972010-10-04 16:33:58 +0200454
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200455 if (preg_match('/<a/i', $str))
Derek Jonese701d762010-03-02 18:17:01 -0600456 {
Andrey Andreevebb3aa02014-03-18 19:18:19 +0200457 $str = preg_replace_callback('#<a[^a-z0-9]+([^>]*?)(?:>|$)#si', array($this, '_js_link_removal'), $str);
Derek Jonese701d762010-03-02 18:17:01 -0600458 }
Barry Mienydd671972010-10-04 16:33:58 +0200459
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200460 if (preg_match('/<img/i', $str))
Derek Jonese701d762010-03-02 18:17:01 -0600461 {
Andrey Andreevebb3aa02014-03-18 19:18:19 +0200462 $str = preg_replace_callback('#<img[^a-z0-9]+([^>]*?)(?:\s?/?>|$)#si', array($this, '_js_img_removal'), $str);
Derek Jonese701d762010-03-02 18:17:01 -0600463 }
Barry Mienydd671972010-10-04 16:33:58 +0200464
vlakoffa81f60c2012-07-02 15:20:11 +0200465 if (preg_match('/script|xss/i', $str))
Derek Jonese701d762010-03-02 18:17:01 -0600466 {
vlakoffa81f60c2012-07-02 15:20:11 +0200467 $str = preg_replace('#</*(?:script|xss).*?>#si', '[removed]', $str);
Derek Jonese701d762010-03-02 18:17:01 -0600468 }
469 }
vlakoffa81f60c2012-07-02 15:20:11 +0200470 while ($original !== $str);
Derek Jonese701d762010-03-02 18:17:01 -0600471
472 unset($original);
473
Pascal Krietec9c045a2011-04-05 14:50:41 -0400474 // Remove evil attributes such as style, onclick and xmlns
475 $str = $this->_remove_evil_attributes($str, $is_image);
Barry Mienydd671972010-10-04 16:33:58 +0200476
Derek Jonese701d762010-03-02 18:17:01 -0600477 /*
478 * Sanitize naughty HTML elements
479 *
480 * If a tag containing any of the words in the list
481 * below is found, the tag gets converted to entities.
482 *
483 * So this: <blink>
484 * Becomes: &lt;blink&gt;
Derek Jonese701d762010-03-02 18:17:01 -0600485 */
Andrey Andreeva30a7172014-02-10 09:17:25 +0200486 $naughty = 'alert|prompt|confirm|applet|audio|basefont|base|behavior|bgsound|blink|body|embed|expression|form|frameset|frame|head|html|ilayer|iframe|input|button|select|isindex|layer|link|meta|keygen|object|plaintext|style|script|textarea|title|math|video|svg|xml|xss';
Derek Jonese701d762010-03-02 18:17:01 -0600487 $str = preg_replace_callback('#<(/*\s*)('.$naughty.')([^><]*)([><]*)#is', array($this, '_sanitize_naughty_html'), $str);
488
489 /*
490 * Sanitize naughty scripting elements
491 *
492 * Similar to above, only instead of looking for
493 * tags it looks for PHP and JavaScript commands
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200494 * that are disallowed. Rather than removing the
Derek Jonese701d762010-03-02 18:17:01 -0600495 * code, it simply converts the parenthesis to entities
496 * rendering the code un-executable.
497 *
498 * For example: eval('some code')
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200499 * Becomes: eval&#40;'some code'&#41;
Derek Jonese701d762010-03-02 18:17:01 -0600500 */
Andrey Andreeva30a7172014-02-10 09:17:25 +0200501 $str = preg_replace('#(alert|prompt|confirm|cmd|passthru|eval|exec|expression|system|fopen|fsockopen|file|file_get_contents|readfile|unlink)(\s*)\((.*?)\)#si',
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200502 '\\1\\2&#40;\\3&#41;',
503 $str);
Barry Mienydd671972010-10-04 16:33:58 +0200504
Pascal Krietec9c045a2011-04-05 14:50:41 -0400505 // Final clean up
506 // This adds a bit of extra precaution in case
507 // something got through the above filters
508 $str = $this->_do_never_allowed($str);
Derek Jonese701d762010-03-02 18:17:01 -0600509
510 /*
Pascal Krietec9c045a2011-04-05 14:50:41 -0400511 * Images are Handled in a Special Way
David Behler07b53422011-08-15 00:25:06 +0200512 * - Essentially, we want to know that after all of the character
513 * conversion is done whether any unwanted, likely XSS, code was found.
Pascal Krietec9c045a2011-04-05 14:50:41 -0400514 * If not, we return TRUE, as the image is clean.
David Behler07b53422011-08-15 00:25:06 +0200515 * However, if the string post-conversion does not matched the
516 * string post-removal of XSS, then it fails, as there was unwanted XSS
Pascal Krietec9c045a2011-04-05 14:50:41 -0400517 * code found and removed/changed during processing.
Derek Jonese701d762010-03-02 18:17:01 -0600518 */
Derek Jonese701d762010-03-02 18:17:01 -0600519 if ($is_image === TRUE)
520 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200521 return ($str === $converted_string);
Derek Jonese701d762010-03-02 18:17:01 -0600522 }
Barry Mienydd671972010-10-04 16:33:58 +0200523
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200524 log_message('debug', 'XSS Filtering completed');
Derek Jonese701d762010-03-02 18:17:01 -0600525 return $str;
526 }
527
528 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200529
Derek Jonese701d762010-03-02 18:17:01 -0600530 /**
Andrey Andreev64354102012-10-28 14:16:02 +0200531 * XSS Hash
Derek Jonese701d762010-03-02 18:17:01 -0600532 *
Andrey Andreev64354102012-10-28 14:16:02 +0200533 * Generates the XSS hash if needed and returns it.
534 *
535 * @see CI_Security::$_xss_hash
536 * @return string XSS hash
Derek Jonese701d762010-03-02 18:17:01 -0600537 */
Eric Barnes9805ecc2011-01-16 23:35:16 -0500538 public function xss_hash()
Barry Mienydd671972010-10-04 16:33:58 +0200539 {
Alex Bilbieed944a32012-06-02 11:07:47 +0100540 if ($this->_xss_hash === '')
Derek Jonese701d762010-03-02 18:17:01 -0600541 {
vlakoff06127562013-03-30 00:06:39 +0100542 $this->_xss_hash = md5(uniqid(mt_rand()));
Derek Jonese701d762010-03-02 18:17:01 -0600543 }
544
Pascal Krietec9c045a2011-04-05 14:50:41 -0400545 return $this->_xss_hash;
Derek Jonese701d762010-03-02 18:17:01 -0600546 }
547
548 // --------------------------------------------------------------------
549
550 /**
Derek Jonesa0911472010-03-30 10:33:09 -0500551 * HTML Entities Decode
552 *
Andrey Andreev64354102012-10-28 14:16:02 +0200553 * A replacement for html_entity_decode()
Derek Jonesa0911472010-03-30 10:33:09 -0500554 *
Pascal Krietec38e3b62011-11-14 13:55:00 -0500555 * The reason we are not using html_entity_decode() by itself is because
556 * while it is not technically correct to leave out the semicolon
557 * at the end of an entity most browsers will still interpret the entity
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200558 * correctly. html_entity_decode() does not convert entities without
Pascal Krietec38e3b62011-11-14 13:55:00 -0500559 * semicolons, so we are left with our own little solution here. Bummer.
Derek Jonesa0911472010-03-30 10:33:09 -0500560 *
Andrey Andreev64354102012-10-28 14:16:02 +0200561 * @link http://php.net/html-entity-decode
562 *
563 * @param string $str Input
564 * @param string $charset Character set
Derek Jonesa0911472010-03-30 10:33:09 -0500565 * @return string
566 */
freewil8cc0cfe2011-08-27 21:53:00 -0400567 public function entity_decode($str, $charset = NULL)
Derek Jonesa0911472010-03-30 10:33:09 -0500568 {
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300569 if (strpos($str, '&') === FALSE)
freewil5c9b0d12011-08-28 12:15:23 -0400570 {
571 return $str;
572 }
Andrey Andreev3d113bd2011-10-05 00:03:20 +0300573
freewil5c9b0d12011-08-28 12:15:23 -0400574 if (empty($charset))
575 {
576 $charset = config_item('charset');
577 }
Barry Mienydd671972010-10-04 16:33:58 +0200578
brian978638a9d22012-12-18 13:25:54 +0200579 do
580 {
Andrey Andreeve7a2aa02014-03-18 18:44:53 +0200581 $str_compare = $str;
brian97807ccbe52012-12-11 20:24:12 +0200582
Andrey Andreeve7a2aa02014-03-18 18:44:53 +0200583 $str = preg_replace('/(&#x0*[0-9a-f]{2,5})(?![0-9a-f;])/iS', '$1;', $str);
584 $str = preg_replace('/(&#\d{2,4})(?![0-9;])/S', '$1;', $str);
brian978638a9d22012-12-18 13:25:54 +0200585 $str = html_entity_decode($str, ENT_COMPAT, $charset);
brian978638a9d22012-12-18 13:25:54 +0200586 }
Andrey Andreeve7a2aa02014-03-18 18:44:53 +0200587 while ($str_compare !== $str);
brian978f50fc732012-12-08 23:22:26 +0200588
brian978638a9d22012-12-18 13:25:54 +0200589 return $str;
Derek Jonesa0911472010-03-30 10:33:09 -0500590 }
Barry Mienydd671972010-10-04 16:33:58 +0200591
Derek Jonesa0911472010-03-30 10:33:09 -0500592 // --------------------------------------------------------------------
Barry Mienydd671972010-10-04 16:33:58 +0200593
Derek Jonesa0911472010-03-30 10:33:09 -0500594 /**
Andrey Andreev64354102012-10-28 14:16:02 +0200595 * Sanitize Filename
Derek Jonese701d762010-03-02 18:17:01 -0600596 *
Andrey Andreev64354102012-10-28 14:16:02 +0200597 * @param string $str Input file name
598 * @param bool $relative_path Whether to preserve paths
Derek Jonese701d762010-03-02 18:17:01 -0600599 * @return string
600 */
Hunter Wu8df33522013-08-03 22:36:05 +0800601 public function sanitize_filename($str, $relative_path = FALSE)
Derek Jonese701d762010-03-02 18:17:01 -0600602 {
Hunter Wu4495cc72013-08-04 12:31:52 +0800603 $bad = $this->filename_bad_chars;
David Behler07b53422011-08-15 00:25:06 +0200604
Derek Jones2ef37592010-10-06 17:51:59 -0500605 if ( ! $relative_path)
606 {
607 $bad[] = './';
608 $bad[] = '/';
609 }
Derek Jonese701d762010-03-02 18:17:01 -0600610
Pascal Krietec9c045a2011-04-05 14:50:41 -0400611 $str = remove_invisible_characters($str, FALSE);
Andrey Andreev7e559772013-01-29 15:38:33 +0200612
613 do
614 {
615 $old = $str;
616 $str = str_replace($bad, '', $str);
617 }
618 while ($old !== $str);
619
620 return stripslashes($str);
Derek Jonese701d762010-03-02 18:17:01 -0600621 }
622
Pascal Krietec9c045a2011-04-05 14:50:41 -0400623 // ----------------------------------------------------------------
624
625 /**
Andrey Andreev1a24a9d2012-06-27 00:52:47 +0300626 * Strip Image Tags
627 *
Andrey Andreev64354102012-10-28 14:16:02 +0200628 * @param string $str
Andrey Andreev1a24a9d2012-06-27 00:52:47 +0300629 * @return string
630 */
631 public function strip_image_tags($str)
632 {
David Cox Jr46e77e02013-10-03 16:56:04 -0400633 return preg_replace(array('#<img[\s/]+.*?src\s*=\s*["\'](.+?)["\'].*?\>#', '#<img[\s/]+.*?src\s*=\s*(.+?).*?\>#'), '\\1', $str);
Andrey Andreev1a24a9d2012-06-27 00:52:47 +0300634 }
635
636 // ----------------------------------------------------------------
637
638 /**
Pascal Krietec9c045a2011-04-05 14:50:41 -0400639 * Compact Exploded Words
640 *
Andrey Andreev64354102012-10-28 14:16:02 +0200641 * Callback method for xss_clean() to remove whitespace from
642 * things like 'j a v a s c r i p t'.
Pascal Krietec9c045a2011-04-05 14:50:41 -0400643 *
Andrey Andreev64354102012-10-28 14:16:02 +0200644 * @used-by CI_Security::xss_clean()
645 * @param array $matches
Timothy Warrenad475052012-04-19 13:21:06 -0400646 * @return string
Pascal Krietec9c045a2011-04-05 14:50:41 -0400647 */
648 protected function _compact_exploded_words($matches)
649 {
650 return preg_replace('/\s+/s', '', $matches[1]).$matches[2];
651 }
652
653 // --------------------------------------------------------------------
David Behler07b53422011-08-15 00:25:06 +0200654
Timothy Warrenad475052012-04-19 13:21:06 -0400655 /**
656 * Remove Evil HTML Attributes (like event handlers and style)
Pascal Krietec9c045a2011-04-05 14:50:41 -0400657 *
658 * It removes the evil attribute and either:
Pascal Krietec9c045a2011-04-05 14:50:41 -0400659 *
Andrey Andreev64354102012-10-28 14:16:02 +0200660 * - Everything up until a space. For example, everything between the pipes:
661 *
662 * <code>
663 * <a |style=document.write('hello');alert('world');| class=link>
664 * </code>
665 *
666 * - Everything inside the quotes. For example, everything between the pipes:
667 *
668 * <code>
669 * <a |style="document.write('hello'); alert('world');"| class="link">
670 * </code>
671 *
672 * @param string $str The string to check
673 * @param bool $is_image Whether the input is an image
674 * @return string The string with the evil attributes removed
Pascal Krietec9c045a2011-04-05 14:50:41 -0400675 */
676 protected function _remove_evil_attributes($str, $is_image)
677 {
Andrey Andreevadf3bde2014-01-25 16:59:17 +0200678 $evil_attributes = array('on\w*', 'style', 'xmlns', 'formaction', 'form', 'xlink:href');
Pascal Krietec9c045a2011-04-05 14:50:41 -0400679
680 if ($is_image === TRUE)
681 {
682 /*
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200683 * Adobe Photoshop puts XML metadata into JFIF images,
Pascal Krietec9c045a2011-04-05 14:50:41 -0400684 * including namespacing, so we have to allow this for images.
685 */
686 unset($evil_attributes[array_search('xmlns', $evil_attributes)]);
687 }
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200688
Pascal Krietec9c045a2011-04-05 14:50:41 -0400689 do {
Pascal Krietec38e3b62011-11-14 13:55:00 -0500690 $count = 0;
691 $attribs = array();
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200692
brian978160c7d12012-12-03 21:18:20 +0200693 // find occurrences of illegal attribute strings with quotes (042 and 047 are octal quotes)
Andrey Andreevdbd999f2014-01-25 22:55:21 +0200694 preg_match_all('/(?<!\w)('.implode('|', $evil_attributes).')\s*=\s*(\042|\047)([^\\2]*?)(\\2)/is', $str, $matches, PREG_SET_ORDER);
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200695
Pascal Krietec38e3b62011-11-14 13:55:00 -0500696 foreach ($matches as $attr)
697 {
698 $attribs[] = preg_quote($attr[0], '/');
699 }
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200700
brian978160c7d12012-12-03 21:18:20 +0200701 // find occurrences of illegal attribute strings without quotes
Andrey Andreevdbd999f2014-01-25 22:55:21 +0200702 preg_match_all('/(?<!\w)('.implode('|', $evil_attributes).')\s*=\s*([^\s>]*)/is', $str, $matches, PREG_SET_ORDER);
David Behler07b53422011-08-15 00:25:06 +0200703
Pascal Krietec38e3b62011-11-14 13:55:00 -0500704 foreach ($matches as $attr)
705 {
706 $attribs[] = preg_quote($attr[0], '/');
707 }
708
709 // replace illegal attribute strings that are inside an html tag
710 if (count($attribs) > 0)
711 {
brian978160c7d12012-12-03 21:18:20 +0200712 $str = preg_replace('/(<?)(\/?[^><]+?)([^A-Za-z<>\-])(.*?)('.implode('|', $attribs).')(.*?)([\s><]?)([><]*)/i', '$1$2 $4$6$7$8', $str, -1, $count);
Pascal Krietec38e3b62011-11-14 13:55:00 -0500713 }
Andrey Andreev72ed4c32012-12-19 17:07:54 +0200714 }
715 while ($count);
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200716
Pascal Krietec9c045a2011-04-05 14:50:41 -0400717 return $str;
718 }
David Behler07b53422011-08-15 00:25:06 +0200719
Pascal Krietec9c045a2011-04-05 14:50:41 -0400720 // --------------------------------------------------------------------
721
722 /**
723 * Sanitize Naughty HTML
724 *
Andrey Andreev64354102012-10-28 14:16:02 +0200725 * Callback method for xss_clean() to remove naughty HTML elements.
Pascal Krietec9c045a2011-04-05 14:50:41 -0400726 *
Andrey Andreev64354102012-10-28 14:16:02 +0200727 * @used-by CI_Security::xss_clean()
728 * @param array $matches
Pascal Krietec9c045a2011-04-05 14:50:41 -0400729 * @return string
730 */
731 protected function _sanitize_naughty_html($matches)
732 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200733 return '&lt;'.$matches[1].$matches[2].$matches[3] // encode opening brace
734 // encode captured opening or closing brace to prevent recursive vectors:
Andrey Andreev67ccdc02012-02-27 23:57:58 +0200735 .str_replace(array('>', '<'), array('&gt;', '&lt;'), $matches[4]);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400736 }
737
738 // --------------------------------------------------------------------
739
740 /**
741 * JS Link Removal
742 *
Andrey Andreev64354102012-10-28 14:16:02 +0200743 * Callback method for xss_clean() to sanitize links.
744 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400745 * This limits the PCRE backtracks, making it more performance friendly
746 * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in
Andrey Andreev64354102012-10-28 14:16:02 +0200747 * PHP 5.2+ on link-heavy strings.
Pascal Krietec9c045a2011-04-05 14:50:41 -0400748 *
Andrey Andreev64354102012-10-28 14:16:02 +0200749 * @used-by CI_Security::xss_clean()
750 * @param array $match
Pascal Krietec9c045a2011-04-05 14:50:41 -0400751 * @return string
752 */
753 protected function _js_link_removal($match)
754 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200755 return str_replace($match[1],
Andrey Andreeva30a7172014-02-10 09:17:25 +0200756 preg_replace('#href=.*?(?:(?:alert|prompt|confirm)(?:\(|&\#40;)|javascript:|livescript:|mocha:|charset=|window\.|document\.|\.cookie|<script|<xss|data\s*:)#si',
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200757 '',
758 $this->_filter_attributes(str_replace(array('<', '>'), '', $match[1]))
759 ),
760 $match[0]);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400761 }
762
763 // --------------------------------------------------------------------
764
765 /**
766 * JS Image Removal
767 *
Andrey Andreev64354102012-10-28 14:16:02 +0200768 * Callback method for xss_clean() to sanitize image tags.
769 *
Pascal Krietec9c045a2011-04-05 14:50:41 -0400770 * This limits the PCRE backtracks, making it more performance friendly
771 * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in
Andrey Andreev64354102012-10-28 14:16:02 +0200772 * PHP 5.2+ on image tag heavy strings.
Pascal Krietec9c045a2011-04-05 14:50:41 -0400773 *
Andrey Andreev64354102012-10-28 14:16:02 +0200774 * @used-by CI_Security::xss_clean()
775 * @param array $match
Pascal Krietec9c045a2011-04-05 14:50:41 -0400776 * @return string
777 */
778 protected function _js_img_removal($match)
779 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200780 return str_replace($match[1],
Andrey Andreeva30a7172014-02-10 09:17:25 +0200781 preg_replace('#src=.*?(?:(?:alert|prompt|confirm)(?:\(|&\#40;)|javascript:|livescript:|mocha:|charset=|window\.|document\.|\.cookie|<script|<xss|base64\s*,)#si',
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200782 '',
783 $this->_filter_attributes(str_replace(array('<', '>'), '', $match[1]))
784 ),
785 $match[0]);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400786 }
787
788 // --------------------------------------------------------------------
789
790 /**
791 * Attribute Conversion
792 *
Andrey Andreev64354102012-10-28 14:16:02 +0200793 * @used-by CI_Security::xss_clean()
794 * @param array $match
Pascal Krietec9c045a2011-04-05 14:50:41 -0400795 * @return string
796 */
797 protected function _convert_attribute($match)
798 {
799 return str_replace(array('>', '<', '\\'), array('&gt;', '&lt;', '\\\\'), $match[0]);
800 }
801
802 // --------------------------------------------------------------------
803
804 /**
805 * Filter Attributes
806 *
Andrey Andreev64354102012-10-28 14:16:02 +0200807 * Filters tag attributes for consistency and safety.
Pascal Krietec9c045a2011-04-05 14:50:41 -0400808 *
Andrey Andreev64354102012-10-28 14:16:02 +0200809 * @used-by CI_Security::_js_img_removal()
810 * @used-by CI_Security::_js_link_removal()
811 * @param string $str
Pascal Krietec9c045a2011-04-05 14:50:41 -0400812 * @return string
813 */
814 protected function _filter_attributes($str)
815 {
816 $out = '';
Pascal Krietec9c045a2011-04-05 14:50:41 -0400817 if (preg_match_all('#\s*[a-z\-]+\s*=\s*(\042|\047)([^\\1]*?)\\1#is', $str, $matches))
818 {
819 foreach ($matches[0] as $match)
820 {
Andrey Andreev4562f2c2012-01-09 23:39:50 +0200821 $out .= preg_replace('#/\*.*?\*/#s', '', $match);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400822 }
823 }
824
825 return $out;
826 }
827
828 // --------------------------------------------------------------------
829
830 /**
831 * HTML Entity Decode Callback
832 *
Andrey Andreev64354102012-10-28 14:16:02 +0200833 * @used-by CI_Security::xss_clean()
834 * @param array $match
Pascal Krietec9c045a2011-04-05 14:50:41 -0400835 * @return string
836 */
837 protected function _decode_entity($match)
838 {
Andrey Andreevc67c3fb2014-01-22 13:26:00 +0200839 // entity_decode() won't convert dangerous HTML5 entities
840 // (it could, but ENT_HTML5 is only available since PHP 5.4),
841 // so we'll do that here
842 return str_ireplace(
843 array_keys($this->html5_entities),
844 array_values($this->html5_entities),
845 $this->entity_decode($match[0], strtoupper(config_item('charset')))
846 );
Pascal Krietec9c045a2011-04-05 14:50:41 -0400847 }
848
849 // --------------------------------------------------------------------
David Behler07b53422011-08-15 00:25:06 +0200850
Pascal Krietec9c045a2011-04-05 14:50:41 -0400851 /**
852 * Validate URL entities
853 *
Andrey Andreev64354102012-10-28 14:16:02 +0200854 * @used-by CI_Security::xss_clean()
855 * @param string $str
Pascal Krietec9c045a2011-04-05 14:50:41 -0400856 * @return string
857 */
858 protected function _validate_entities($str)
859 {
860 /*
861 * Protect GET variables in URLs
862 */
David Behler07b53422011-08-15 00:25:06 +0200863
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200864 // 901119URL5918AMP18930PROTECT8198
865 $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 -0400866
867 /*
868 * Validate standard character entities
869 *
Derek Jones37f4b9c2011-07-01 17:56:50 -0500870 * Add a semicolon if missing. We do this to enable
Pascal Krietec9c045a2011-04-05 14:50:41 -0400871 * the conversion of entities to ASCII later.
Pascal Krietec9c045a2011-04-05 14:50:41 -0400872 */
Andrey Andreev4d057162014-01-20 11:17:34 +0200873 $str = preg_replace('/(&#\d{2,4})(?![0-9;])/', '$1;', $str);
874 $str = preg_replace('/(&[a-z]{2,})(?![a-z;])/i', '$1;', $str);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400875
876 /*
877 * Validate UTF16 two byte encoding (x00)
878 *
879 * Just as above, adds a semicolon if missing.
Pascal Krietec9c045a2011-04-05 14:50:41 -0400880 */
Andrey Andreev4d057162014-01-20 11:17:34 +0200881 $str = preg_replace('/(&#x0*[0-9a-f]{2,5})(?![0-9a-f;])/i', '$1;', $str);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400882
883 /*
884 * Un-Protect GET variables in URLs
885 */
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200886 return str_replace($this->xss_hash(), '&', $str);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400887 }
888
889 // ----------------------------------------------------------------------
890
891 /**
892 * Do Never Allowed
893 *
Andrey Andreev64354102012-10-28 14:16:02 +0200894 * @used-by CI_Security::xss_clean()
Pascal Krietec9c045a2011-04-05 14:50:41 -0400895 * @param string
896 * @return string
897 */
898 protected function _do_never_allowed($str)
899 {
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200900 $str = str_replace(array_keys($this->_never_allowed_str), $this->_never_allowed_str, $str);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400901
Andrey Andreevbb488dc2012-01-07 23:35:16 +0200902 foreach ($this->_never_allowed_regex as $regex)
Pascal Krietec9c045a2011-04-05 14:50:41 -0400903 {
Wes Baker5335bc32012-04-24 15:17:14 -0400904 $str = preg_replace('#'.$regex.'#is', '[removed]', $str);
Pascal Krietec9c045a2011-04-05 14:50:41 -0400905 }
David Behler07b53422011-08-15 00:25:06 +0200906
Pascal Krietec9c045a2011-04-05 14:50:41 -0400907 return $str;
908 }
909
910 // --------------------------------------------------------------------
911
912 /**
Andrey Andreev64354102012-10-28 14:16:02 +0200913 * Set CSRF Hash and Cookie
Pascal Krietec9c045a2011-04-05 14:50:41 -0400914 *
915 * @return string
916 */
917 protected function _csrf_set_hash()
918 {
Alex Bilbieed944a32012-06-02 11:07:47 +0100919 if ($this->_csrf_hash === '')
Pascal Krietec9c045a2011-04-05 14:50:41 -0400920 {
vlakoff3a3d5f62013-10-17 22:22:16 +0200921 // If the cookie exists we will use its value.
Pascal Krietec9c045a2011-04-05 14:50:41 -0400922 // We don't necessarily want to regenerate it with
David Behler07b53422011-08-15 00:25:06 +0200923 // each page load since a page could contain embedded
Pascal Krietec9c045a2011-04-05 14:50:41 -0400924 // sub-pages causing this feature to fail
David Behler07b53422011-08-15 00:25:06 +0200925 if (isset($_COOKIE[$this->_csrf_cookie_name]) &&
Alexander Hofstedee2c374f2012-05-17 00:28:08 +0200926 preg_match('#^[0-9a-f]{32}$#iS', $_COOKIE[$this->_csrf_cookie_name]) === 1)
Pascal Krietec9c045a2011-04-05 14:50:41 -0400927 {
928 return $this->_csrf_hash = $_COOKIE[$this->_csrf_cookie_name];
929 }
David Behler07b53422011-08-15 00:25:06 +0200930
vlakoff3a3d5f62013-10-17 22:22:16 +0200931 $this->_csrf_hash = md5(uniqid(mt_rand(), TRUE));
Chris Berthed93e6f32011-09-25 10:33:25 -0400932 $this->csrf_set_cookie();
Pascal Krietec9c045a2011-04-05 14:50:41 -0400933 }
934
935 return $this->_csrf_hash;
936 }
937
Derek Jonese701d762010-03-02 18:17:01 -0600938}
Derek Jonese701d762010-03-02 18:17:01 -0600939
940/* End of file Security.php */
Andrey Andreev9ba661b2012-06-04 14:44:34 +0300941/* Location: ./system/core/Security.php */