]>
jfr.im git - z_archive/KronOS.git/blob - video/system/core/Security.php
1 <?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
5 * An open source application development framework for PHP 5.1.6 or newer
8 * @author ExpressionEngine Dev Team
9 * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
10 * @license http://codeigniter.com/user_guide/license.html
11 * @link http://codeigniter.com
16 // ------------------------------------------------------------------------
21 * @package CodeIgniter
22 * @subpackage Libraries
24 * @author ExpressionEngine Dev Team
25 * @link http://codeigniter.com/user_guide/libraries/security.html
30 * Random Hash for protecting URLs
35 protected $_xss_hash = '';
37 * Random Hash for Cross Site Request Forgery Protection Cookie
42 protected $_csrf_hash = '';
44 * Expiration time for Cross Site Request Forgery Protection Cookie
45 * Defaults to two hours (in seconds)
50 protected $_csrf_expire = 7200;
52 * Token name for Cross Site Request Forgery Protection Cookie
57 protected $_csrf_token_name = 'ci_csrf_token';
59 * Cookie name for Cross Site Request Forgery Protection Cookie
64 protected $_csrf_cookie_name = 'ci_csrf_token';
66 * List of never allowed strings
71 protected $_never_allowed_str = array(
72 'document.cookie' => '[removed]',
73 'document.write' => '[removed]',
74 '.parentNode' => '[removed]',
75 '.innerHTML' => '[removed]',
76 'window.location' => '[removed]',
77 '-moz-binding' => '[removed]',
80 '<![CDATA[' => '<![CDATA[',
81 '<comment>' => '<comment>'
84 /* never allowed, regex replacement */
86 * List of never allowed regex replacement
91 protected $_never_allowed_regex = array(
93 'expression\s*(\(|&\#40;)', // CSS and IE
94 'vbscript\s*:', // IE, surprise!
96 "([\"'])?data\s*:[^\\1]*?base64[^\\1]*?,[^\\1]*?\\1?"
104 public function __construct()
106 // Is CSRF protection enabled?
107 if (config_item('csrf_protection') === TRUE)
110 foreach (array('csrf_expire', 'csrf_token_name', 'csrf_cookie_name') as $key)
112 if (FALSE !== ($val = config_item($key)))
114 $this->{'_'.$key
} = $val;
118 // Append application specific cookie prefix
119 if (config_item('cookie_prefix'))
121 $this->_csrf_cookie_name
= config_item('cookie_prefix').$this->_csrf_cookie_name
;
125 $this->_csrf_set_hash();
128 log_message('debug', "Security Class Initialized");
131 // --------------------------------------------------------------------
134 * Verify Cross Site Request Forgery Protection
138 public function csrf_verify()
140 // If it's not a POST request we will set the CSRF cookie
141 if (strtoupper($_SERVER['REQUEST_METHOD']) !== 'POST')
143 return $this->csrf_set_cookie();
146 // Do the tokens exist in both the _POST and _COOKIE arrays?
147 if ( ! isset($_POST[$this->_csrf_token_name
], $_COOKIE[$this->_csrf_cookie_name
]))
149 $this->csrf_show_error();
152 // Do the tokens match?
153 if ($_POST[$this->_csrf_token_name
] != $_COOKIE[$this->_csrf_cookie_name
])
155 $this->csrf_show_error();
158 // We kill this since we're done and we don't want to
159 // polute the _POST array
160 unset($_POST[$this->_csrf_token_name
]);
162 // Nothing should last forever
163 unset($_COOKIE[$this->_csrf_cookie_name
]);
164 $this->_csrf_set_hash();
165 $this->csrf_set_cookie();
167 log_message('debug', 'CSRF token verified');
172 // --------------------------------------------------------------------
175 * Set Cross Site Request Forgery Protection Cookie
179 public function csrf_set_cookie()
181 $expire = time() +
$this->_csrf_expire
;
182 $secure_cookie = (config_item('cookie_secure') === TRUE) ? 1 : 0;
184 if ($secure_cookie && (empty($_SERVER['HTTPS']) OR strtolower($_SERVER['HTTPS']) === 'off'))
189 setcookie($this->_csrf_cookie_name
, $this->_csrf_hash
, $expire, config_item('cookie_path'), config_item('cookie_domain'), $secure_cookie);
191 log_message('debug', "CRSF cookie Set");
196 // --------------------------------------------------------------------
203 public function csrf_show_error()
205 show_error('The action you have requested is not allowed.');
208 // --------------------------------------------------------------------
215 * @return string self::_csrf_hash
217 public function get_csrf_hash()
219 return $this->_csrf_hash
;
222 // --------------------------------------------------------------------
225 * Get CSRF Token Name
229 * @return string self::csrf_token_name
231 public function get_csrf_token_name()
233 return $this->_csrf_token_name
;
236 // --------------------------------------------------------------------
241 * Sanitizes data so that Cross Site Scripting Hacks can be
242 * prevented. This function does a fair amount of work but
243 * it is extremely thorough, designed to prevent even the
244 * most obscure XSS attempts. Nothing is ever 100% foolproof,
245 * of course, but I haven't been able to get anything passed
248 * Note: This function should only be used to deal with data
249 * upon submission. It's not something that should
250 * be used for general runtime processing.
252 * This function was based in part on some code and ideas I
253 * got from Bitflux: http://channel.bitflux.ch/wiki/XSS_Prevention
255 * To help develop this script I used this great list of
256 * vulnerabilities along with a few other hacks I've
257 * harvested from examining vulnerabilities in other programs:
258 * http://ha.ckers.org/xss.html
260 * @param mixed string or array
264 public function xss_clean($str, $is_image = FALSE)
267 * Is the string an array?
272 while (list($key) = each($str))
274 $str[$key] = $this->xss_clean($str[$key]);
281 * Remove Invisible Characters
283 $str = remove_invisible_characters($str);
285 // Validate Entities in URLs
286 $str = $this->_validate_entities($str);
291 * Just in case stuff like this is submitted:
293 * <a href="http://%77%77%77%2E%67%6F%6F%67%6C%65%2E%63%6F%6D">Google</a>
295 * Note: Use rawurldecode() so it does not remove plus signs
298 $str = rawurldecode($str);
301 * Convert character entities to ASCII
303 * This permits our tests below to work reliably.
304 * We only convert entities that are within tags since
305 * these are the ones that will pose security problems.
309 $str = preg_replace_callback("/[a-z]+=([\'\"]).*?\\1/si", array($this, '_convert_attribute'), $str);
311 $str = preg_replace_callback("/<\w+.*?(?=>|<|$)/si", array($this, '_decode_entity'), $str);
314 * Remove Invisible Characters Again!
316 $str = remove_invisible_characters($str);
319 * Convert all tabs to spaces
321 * This prevents strings like this: ja vascript
322 * NOTE: we deal with spaces between characters later.
323 * NOTE: preg_replace was found to be amazingly slow here on
324 * large blocks of data, so we use str_replace.
327 if (strpos($str, "\t") !== FALSE)
329 $str = str_replace("\t", ' ', $str);
333 * Capture converted string for later comparison
335 $converted_string = $str;
337 // Remove Strings that are never allowed
338 $str = $this->_do_never_allowed($str);
341 * Makes PHP tags safe
343 * Note: XML tags are inadvertently replaced too:
347 * But it doesn't seem to pose a problem.
349 if ($is_image === TRUE)
351 // Images have a tendency to have the PHP short opening and
352 // closing tags every so often so we skip those and only
353 // do the long opening tags.
354 $str = preg_replace('/<\?(php)/i', "<?\\1", $str);
358 $str = str_replace(array('<?', '?'.'>'), array('<?', '?>'), $str);
362 * Compact any exploded words
364 * This corrects words like: j a v a s c r i p t
365 * These words are compacted back to their correct state.
368 'javascript', 'expression', 'vbscript', 'script', 'base64',
369 'applet', 'alert', 'document', 'write', 'cookie', 'window'
372 foreach ($words as $word)
376 for ($i = 0, $wordlen = strlen($word); $i < $wordlen; $i++
)
378 $temp .= substr($word, $i, 1)."\s*";
381 // We only want to do this when it is followed by a non-word character
382 // That way valid stuff like "dealer to" does not become "dealerto"
383 $str = preg_replace_callback('#('.substr($temp, 0, -3).')(\W)#is', array($this, '_compact_exploded_words'), $str);
387 * Remove disallowed Javascript in links or img tags
388 * We used to do some version comparisons and use of stripos for PHP5,
389 * but it is dog slow compared to these simplified non-capturing
390 * preg_match(), especially if the pattern exists in the string
396 if (preg_match("/<a/i", $str))
398 $str = preg_replace_callback("#<a\s+([^>]*?)(>|$)#si", array($this, '_js_link_removal'), $str);
401 if (preg_match("/<img/i", $str))
403 $str = preg_replace_callback("#<img\s+([^>]*?)(\s?/?>|$)#si", array($this, '_js_img_removal'), $str);
406 if (preg_match("/script/i", $str) OR preg_match("/xss/i", $str))
408 $str = preg_replace("#<(/*)(script|xss)(.*?)\>#si", '[removed]', $str);
411 while($original != $str);
415 // Remove evil attributes such as style, onclick and xmlns
416 $str = $this->_remove_evil_attributes($str, $is_image);
419 * Sanitize naughty HTML elements
421 * If a tag containing any of the words in the list
422 * below is found, the tag gets converted to entities.
425 * Becomes: <blink>
427 $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';
428 $str = preg_replace_callback('#<(/*\s*)('.$naughty.')([^><]*)([><]*)#is', array($this, '_sanitize_naughty_html'), $str);
431 * Sanitize naughty scripting elements
433 * Similar to above, only instead of looking for
434 * tags it looks for PHP and JavaScript commands
435 * that are disallowed. Rather than removing the
436 * code, it simply converts the parenthesis to entities
437 * rendering the code un-executable.
439 * For example: eval('some code')
440 * Becomes: eval('some code')
442 $str = preg_replace('#(alert|cmd|passthru|eval|exec|expression|system|fopen|fsockopen|file|file_get_contents|readfile|unlink)(\s*)\((.*?)\)#si', "\\1\\2(\\3)", $str);
446 // This adds a bit of extra precaution in case
447 // something got through the above filters
448 $str = $this->_do_never_allowed($str);
451 * Images are Handled in a Special Way
452 * - Essentially, we want to know that after all of the character
453 * conversion is done whether any unwanted, likely XSS, code was found.
454 * If not, we return TRUE, as the image is clean.
455 * However, if the string post-conversion does not matched the
456 * string post-removal of XSS, then it fails, as there was unwanted XSS
457 * code found and removed/changed during processing.
460 if ($is_image === TRUE)
462 return ($str == $converted_string) ? TRUE: FALSE;
465 log_message('debug', "XSS Filtering completed");
469 // --------------------------------------------------------------------
472 * Random Hash for protecting URLs
476 public function xss_hash()
478 if ($this->_xss_hash
== '')
481 $this->_xss_hash
= md5(time() +
mt_rand(0, 1999999999));
484 return $this->_xss_hash
;
487 // --------------------------------------------------------------------
490 * HTML Entities Decode
492 * This function is a replacement for html_entity_decode()
494 * The reason we are not using html_entity_decode() by itself is because
495 * while it is not technically correct to leave out the semicolon
496 * at the end of an entity most browsers will still interpret the entity
497 * correctly. html_entity_decode() does not convert entities without
498 * semicolons, so we are left with our own little solution here. Bummer.
504 public function entity_decode($str, $charset='UTF-8')
506 if (stristr($str, '&') === FALSE)
511 $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);
516 // --------------------------------------------------------------------
525 public function sanitize_filename($str, $relative_path = FALSE)
561 if ( ! $relative_path)
567 $str = remove_invisible_characters($str, FALSE);
568 return stripslashes(str_replace($bad, '', $str));
571 // ----------------------------------------------------------------
574 * Compact Exploded Words
576 * Callback function for xss_clean() to remove whitespace from
577 * things like j a v a s c r i p t
582 protected function _compact_exploded_words($matches)
584 return preg_replace('/\s+/s', '', $matches[1]).$matches[2];
587 // --------------------------------------------------------------------
590 * Remove Evil HTML Attributes (like evenhandlers and style)
592 * It removes the evil attribute and either:
593 * - Everything up until a space
594 * For example, everything between the pipes:
595 * <a |style=document.write('hello');alert('world');| class=link>
596 * - Everything inside the quotes
597 * For example, everything between the pipes:
598 * <a |style="document.write('hello'); alert('world');"| class="link">
600 * @param string $str The string to check
601 * @param boolean $is_image TRUE if this is an image
602 * @return string The string with the evil attributes removed
604 protected function _remove_evil_attributes($str, $is_image)
606 // All javascript event handlers (e.g. onload, onclick, onmouseover), style, and xmlns
607 $evil_attributes = array('on\w*', 'style', 'xmlns', 'formaction');
609 if ($is_image === TRUE)
612 * Adobe Photoshop puts XML metadata into JFIF images,
613 * including namespacing, so we have to allow this for images.
615 unset($evil_attributes[array_search('xmlns', $evil_attributes)]);
622 // find occurrences of illegal attribute strings without quotes
623 preg_match_all('/('.implode('|', $evil_attributes).')\s*=\s*([^\s>]*)/is', $str, $matches, PREG_SET_ORDER
);
625 foreach ($matches as $attr)
628 $attribs[] = preg_quote($attr[0], '/');
631 // find occurrences of illegal attribute strings with quotes (042 and 047 are octal quotes)
632 preg_match_all("/(".implode('|', $evil_attributes).")\s*=\s*(\042|\047)([^\\2]*?)(\\2)/is", $str, $matches, PREG_SET_ORDER
);
634 foreach ($matches as $attr)
636 $attribs[] = preg_quote($attr[0], '/');
639 // replace illegal attribute strings that are inside an html tag
640 if (count($attribs) > 0)
642 $str = preg_replace("/<(\/?[^><]+?)([^A-Za-z<>\-])(.*?)(".implode('|', $attribs).")(.*?)([\s><])([><]*)/i", '<$1 $3$5$6$7', $str, -1, $count);
650 // --------------------------------------------------------------------
653 * Sanitize Naughty HTML
655 * Callback function for xss_clean() to remove naughty HTML elements
660 protected function _sanitize_naughty_html($matches)
662 // encode opening brace
663 $str = '<
;'.$matches[1].$matches[2].$matches[3];
665 // encode captured opening or closing brace to prevent recursive vectors
666 $str .= str_replace(array('>', '<'), array('>
;', '<
;'),
672 // --------------------------------------------------------------------
677 * Callback function for xss_clean() to sanitize links
678 * This limits the PCRE backtracks, making it more performance friendly
679 * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in
680 * PHP 5.2+ on link-heavy strings
685 protected function _js_link_removal($match)
690 '#href=.*?(alert\(|alert&\#40;|javascript\:|livescript\:|mocha\:|charset\=|window\.|document\.|\.cookie|<script|<xss|data\s*:)#si',
692 $this->_filter_attributes(str_replace(array('<', '>'), '', $match[1]))
698 // --------------------------------------------------------------------
703 * Callback function for xss_clean() to sanitize image tags
704 * This limits the PCRE backtracks, making it more performance friendly
705 * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in
706 * PHP 5.2+ on image tag heavy strings
711 protected function _js_img_removal($match)
716 '#src=.*?(alert\(|alert&\#40;|javascript\:|livescript\:|mocha\:|charset\=|window\.|document\.|\.cookie|<script|<xss|base64\s*,)#si',
718 $this->_filter_attributes(str_replace(array('<', '>'), '', $match[1]))
724 // --------------------------------------------------------------------
727 * Attribute Conversion
729 * Used as a callback for XSS Clean
734 protected function _convert_attribute($match)
736 return str_replace(array('>', '<', '\\'), array('>', '<', '\\\\'), $match[0]);
739 // --------------------------------------------------------------------
744 * Filters tag attributes for consistency and safety
749 protected function _filter_attributes($str)
753 if (preg_match_all('#\s*[a-z\-]+\s*=\s*(\042|\047)([^\\1]*?)\\1#is', $str, $matches))
755 foreach ($matches[0] as $match)
757 $out .= preg_replace("#/\*.*?\*/#s", '', $match);
764 // --------------------------------------------------------------------
767 * HTML Entity Decode Callback
769 * Used as a callback for XSS Clean
774 protected function _decode_entity($match)
776 return $this->entity_decode($match[0], strtoupper(config_item('charset')));
779 // --------------------------------------------------------------------
782 * Validate URL entities
784 * Called by xss_clean()
789 protected function _validate_entities($str)
792 * Protect GET variables in URLs
795 // 901119URL5918AMP18930PROTECT8198
797 $str = preg_replace('|\&([a-z\_0-9\-]+)\=([a-z\_0-9\-]+)|i', $this->xss_hash()."\\1=\\2", $str);
800 * Validate standard character entities
802 * Add a semicolon if missing. We do this to enable
803 * the conversion of entities to ASCII later.
806 $str = preg_replace('#(&\#?[0-9a-z]{2,})([\x00-\x20])*;?#i', "\\1;\\2", $str);
809 * Validate UTF16 two byte encoding (x00)
811 * Just as above, adds a semicolon if missing.
814 $str = preg_replace('#(&\#x?)([0-9A-F]+);?#i',"\\1\\2;",$str);
817 * Un-Protect GET variables in URLs
819 $str = str_replace($this->xss_hash(), '&', $str);
824 // ----------------------------------------------------------------------
829 * A utility function for xss_clean()
834 protected function _do_never_allowed($str)
836 $str = str_replace(array_keys($this->_never_allowed_str
), $this->_never_allowed_str
, $str);
838 foreach ($this->_never_allowed_regex
as $regex)
840 $str = preg_replace('#'.$regex.'#is', '[removed]', $str);
846 // --------------------------------------------------------------------
849 * Set Cross Site Request Forgery Protection Cookie
853 protected function _csrf_set_hash()
855 if ($this->_csrf_hash
== '')
857 // If the cookie exists we will use it's value.
858 // We don't necessarily want to regenerate it with
859 // each page load since a page could contain embedded
860 // sub-pages causing this feature to fail
861 if (isset($_COOKIE[$this->_csrf_cookie_name
]) &&
862 preg_match('#^[0-9a-f]{32}$#iS', $_COOKIE[$this->_csrf_cookie_name
]) === 1)
864 return $this->_csrf_hash
= $_COOKIE[$this->_csrf_cookie_name
];
867 return $this->_csrf_hash
= md5(uniqid(rand(), TRUE));
870 return $this->_csrf_hash
;
875 /* End of file Security.php */
876 /* Location: ./system/libraries/Security.php */