作者 Karson

新增安全过滤类

@@ -408,3 +408,13 @@ if (!function_exists('check_cors_request')) { @@ -408,3 +408,13 @@ if (!function_exists('check_cors_request')) {
408 } 408 }
409 } 409 }
410 } 410 }
  411 +
  412 +if (!function_exists('xss_clean')) {
  413 + /**
  414 + * 清理XSS
  415 + */
  416 + function xss_clean($content, $is_image = false)
  417 + {
  418 + return \app\common\library\Security::instance()->xss_clean($content, $is_image);
  419 + }
  420 +}
  1 +<?php
  2 +
  3 +namespace app\common\library;
  4 +
  5 +use Exception;
  6 +
  7 +/**
  8 + * 安全过滤类
  9 + *
  10 + * @category Security
  11 + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/)
  12 + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/)
  13 + * @license https://opensource.org/licenses/MIT MIT License
  14 + * @link https://codeigniter.com
  15 + * @author EllisLab Dev Team
  16 + */
  17 +class Security
  18 +{
  19 +
  20 + protected static $instance = null;
  21 +
  22 + /**
  23 + * List of sanitize filename strings
  24 + *
  25 + * @var array
  26 + */
  27 + public $filename_bad_chars = array(
  28 + '../',
  29 + '<!--',
  30 + '-->',
  31 + '<',
  32 + '>',
  33 + "'",
  34 + '"',
  35 + '&',
  36 + '$',
  37 + '#',
  38 + '{',
  39 + '}',
  40 + '[',
  41 + ']',
  42 + '=',
  43 + ';',
  44 + '?',
  45 + '%20',
  46 + '%22',
  47 + '%3c', // <
  48 + '%253c', // <
  49 + '%3e', // >
  50 + '%0e', // >
  51 + '%28', // (
  52 + '%29', // )
  53 + '%2528', // (
  54 + '%26', // &
  55 + '%24', // $
  56 + '%3f', // ?
  57 + '%3b', // ;
  58 + '%3d' // =
  59 + );
  60 +
  61 + /**
  62 + * Character set
  63 + *
  64 + * Will be overridden by the constructor.
  65 + *
  66 + * @var string
  67 + */
  68 + public $charset = 'UTF-8';
  69 +
  70 + /**
  71 + * XSS Hash
  72 + *
  73 + * Random Hash for protecting URLs.
  74 + *
  75 + * @var string
  76 + */
  77 + protected $_xss_hash;
  78 +
  79 + /**
  80 + * List of never allowed strings
  81 + *
  82 + * @var array
  83 + */
  84 + protected $_never_allowed_str = array(
  85 + 'document.cookie' => '[removed]',
  86 + '(document).cookie' => '[removed]',
  87 + 'document.write' => '[removed]',
  88 + '(document).write' => '[removed]',
  89 + '.parentNode' => '[removed]',
  90 + '.innerHTML' => '[removed]',
  91 + '-moz-binding' => '[removed]',
  92 + '<!--' => '&lt;!--',
  93 + '-->' => '--&gt;',
  94 + '<![CDATA[' => '&lt;![CDATA[',
  95 + '<comment>' => '&lt;comment&gt;',
  96 + '<%' => '&lt;&#37;'
  97 + );
  98 +
  99 + /**
  100 + * List of never allowed regex replacements
  101 + *
  102 + * @var array
  103 + */
  104 + protected $_never_allowed_regex = array(
  105 + 'javascript\s*:',
  106 + '(\(?document\)?|\(?window\)?(\.document)?)\.(location|on\w*)',
  107 + 'expression\s*(\(|&\#40;)', // CSS and IE
  108 + 'vbscript\s*:', // IE, surprise!
  109 + 'wscript\s*:', // IE
  110 + 'jscript\s*:', // IE
  111 + 'vbs\s*:', // IE
  112 + 'Redirect\s+30\d',
  113 + "([\"'])?data\s*:[^\\1]*?base64[^\\1]*?,[^\\1]*?\\1?"
  114 + );
  115 +
  116 + protected $options = [
  117 + 'placeholder' => '[removed]'
  118 + ];
  119 +
  120 + /**
  121 + * Class constructor
  122 + *
  123 + * @return void
  124 + */
  125 + public function __construct($options = [])
  126 + {
  127 + $this->options = array_merge($this->options, $options);
  128 + foreach ($this->_never_allowed_str as $index => &$item) {
  129 + $item = str_replace('[removed]', $this->options['placeholder'], $item);
  130 + }
  131 + }
  132 +
  133 + /**
  134 + *
  135 + * @param array $options 参数
  136 + * @return Security
  137 + */
  138 + public static function instance($options = [])
  139 + {
  140 + if (is_null(self::$instance)) {
  141 + self::$instance = new static($options);
  142 + }
  143 +
  144 + return self::$instance;
  145 + }
  146 +
  147 + /**
  148 + * XSS Clean
  149 + *
  150 + * Sanitizes data so that Cross Site Scripting Hacks can be
  151 + * prevented. This method does a fair amount of work but
  152 + * it is extremely thorough, designed to prevent even the
  153 + * most obscure XSS attempts. Nothing is ever 100% foolproof,
  154 + * of course, but I haven't been able to get anything passed
  155 + * the filter.
  156 + *
  157 + * Note: Should only be used to deal with data upon submission.
  158 + * It's not something that should be used for general
  159 + * runtime processing.
  160 + *
  161 + * @link http://channel.bitflux.ch/wiki/XSS_Prevention
  162 + * Based in part on some code and ideas from Bitflux.
  163 + *
  164 + * @link http://ha.ckers.org/xss.html
  165 + * To help develop this script I used this great list of
  166 + * vulnerabilities along with a few other hacks I've
  167 + * harvested from examining vulnerabilities in other programs.
  168 + *
  169 + * @param string|string[] $str Input data
  170 + * @param bool $is_image Whether the input is an image
  171 + * @return string
  172 + */
  173 + public function xss_clean($str, $is_image = false)
  174 + {
  175 + // Is the string an array?
  176 + if (is_array($str)) {
  177 + foreach ($str as $key => &$value) {
  178 + $str[$key] = $this->xss_clean($value);
  179 + }
  180 +
  181 + return $str;
  182 + }
  183 +
  184 + // Remove Invisible Characters
  185 + $str = $this->remove_invisible_characters($str);
  186 +
  187 + /*
  188 + * URL Decode
  189 + *
  190 + * Just in case stuff like this is submitted:
  191 + *
  192 + * <a href="http://%77%77%77%2E%67%6F%6F%67%6C%65%2E%63%6F%6D">Google</a>
  193 + *
  194 + * Note: Use rawurldecode() so it does not remove plus signs
  195 + */
  196 + if (stripos($str, '%') !== false) {
  197 + do {
  198 + $oldstr = $str;
  199 + $str = rawurldecode($str);
  200 + $str = preg_replace_callback('#%(?:\s*[0-9a-f]){2,}#i', array($this, '_urldecodespaces'), $str);
  201 + } while ($oldstr !== $str);
  202 + unset($oldstr);
  203 + }
  204 +
  205 + /*
  206 + * Convert character entities to ASCII
  207 + *
  208 + * This permits our tests below to work reliably.
  209 + * We only convert entities that are within tags since
  210 + * these are the ones that will pose security problems.
  211 + */
  212 + $str = preg_replace_callback("/[^a-z0-9>]+[a-z0-9]+=([\'\"]).*?\\1/si", array($this, '_convert_attribute'), $str);
  213 + $str = preg_replace_callback('/<\w+.*/si', array($this, '_decode_entity'), $str);
  214 +
  215 + // Remove Invisible Characters Again!
  216 + $str = $this->remove_invisible_characters($str);
  217 +
  218 + /*
  219 + * Convert all tabs to spaces
  220 + *
  221 + * This prevents strings like this: ja vascript
  222 + * NOTE: we deal with spaces between characters later.
  223 + * NOTE: preg_replace was found to be amazingly slow here on
  224 + * large blocks of data, so we use str_replace.
  225 + */
  226 + $str = str_replace("\t", ' ', $str);
  227 +
  228 + // Capture converted string for later comparison
  229 + $converted_string = $str;
  230 +
  231 + // Remove Strings that are never allowed
  232 + $str = $this->_do_never_allowed($str);
  233 +
  234 + /*
  235 + * Makes PHP tags safe
  236 + *
  237 + * Note: XML tags are inadvertently replaced too:
  238 + *
  239 + * <?xml
  240 + *
  241 + * But it doesn't seem to pose a problem.
  242 + */
  243 + if ($is_image === true) {
  244 + // Images have a tendency to have the PHP short opening and
  245 + // closing tags every so often so we skip those and only
  246 + // do the long opening tags.
  247 + $str = preg_replace('/<\?(php)/i', '&lt;?\\1', $str);
  248 + } else {
  249 + $str = str_replace(array('<?', '?' . '>'), array('&lt;?', '?&gt;'), $str);
  250 + }
  251 +
  252 + /*
  253 + * Compact any exploded words
  254 + *
  255 + * This corrects words like: j a v a s c r i p t
  256 + * These words are compacted back to their correct state.
  257 + */
  258 + $words = array(
  259 + 'javascript',
  260 + 'expression',
  261 + 'vbscript',
  262 + 'jscript',
  263 + 'wscript',
  264 + 'vbs',
  265 + 'script',
  266 + 'base64',
  267 + 'applet',
  268 + 'alert',
  269 + 'document',
  270 + 'write',
  271 + 'cookie',
  272 + 'window',
  273 + 'confirm',
  274 + 'prompt',
  275 + 'eval'
  276 + );
  277 +
  278 + foreach ($words as $word) {
  279 + $word = implode('\s*', str_split($word)) . '\s*';
  280 +
  281 + // We only want to do this when it is followed by a non-word character
  282 + // That way valid stuff like "dealer to" does not become "dealerto"
  283 + $str = preg_replace_callback('#(' . substr($word, 0, -3) . ')(\W)#is', array($this, '_compact_exploded_words'), $str);
  284 + }
  285 +
  286 + /*
  287 + * Remove disallowed Javascript in links or img tags
  288 + * We used to do some version comparisons and use of stripos(),
  289 + * but it is dog slow compared to these simplified non-capturing
  290 + * preg_match(), especially if the pattern exists in the string
  291 + *
  292 + * Note: It was reported that not only space characters, but all in
  293 + * the following pattern can be parsed as separators between a tag name
  294 + * and its attributes: [\d\s"\'`;,\/\=\(\x00\x0B\x09\x0C]
  295 + * ... however, $this->remove_invisible_characters() above already strips the
  296 + * hex-encoded ones, so we'll skip them below.
  297 + */
  298 + do {
  299 + $original = $str;
  300 +
  301 + if (preg_match('/<a/i', $str)) {
  302 + $str = preg_replace_callback('#<a(?:rea)?[^a-z0-9>]+([^>]*?)(?:>|$)#si', array($this, '_js_link_removal'), $str);
  303 + }
  304 +
  305 + if (preg_match('/<img/i', $str)) {
  306 + $str = preg_replace_callback('#<img[^a-z0-9]+([^>]*?)(?:\s?/?>|$)#si', array($this, '_js_img_removal'), $str);
  307 + }
  308 +
  309 + if (preg_match('/script|xss/i', $str)) {
  310 + $str = preg_replace('#</*(?:script|xss).*?>#si', $this->options['placeholder'], $str);
  311 + }
  312 + } while ($original !== $str);
  313 + unset($original);
  314 +
  315 + /*
  316 + * Sanitize naughty HTML elements
  317 + *
  318 + * If a tag containing any of the words in the list
  319 + * below is found, the tag gets converted to entities.
  320 + *
  321 + * So this: <blink>
  322 + * Becomes: &lt;blink&gt;
  323 + */
  324 + $pattern = '#'
  325 + . '<((?<slash>/*\s*)((?<tagName>[a-z0-9]+)(?=[^a-z0-9]|$)|.+)' // tag start and name, followed by a non-tag character
  326 + . '[^\s\042\047a-z0-9>/=]*' // a valid attribute character immediately after the tag would count as a separator
  327 + // optional attributes
  328 + . '(?<attributes>(?:[\s\042\047/=]*' // non-attribute characters, excluding > (tag close) for obvious reasons
  329 + . '[^\s\042\047>/=]+' // attribute characters
  330 + // optional attribute-value
  331 + . '(?:\s*=' // attribute-value separator
  332 + . '(?:[^\s\042\047=><`]+|\s*\042[^\042]*\042|\s*\047[^\047]*\047|\s*(?U:[^\s\042\047=><`]*))' // single, double or non-quoted value
  333 + . ')?' // end optional attribute-value group
  334 + . ')*)' // end optional attributes group
  335 + . '[^>]*)(?<closeTag>\>)?#isS';
  336 +
  337 + // Note: It would be nice to optimize this for speed, BUT
  338 + // only matching the naughty elements here results in
  339 + // false positives and in turn - vulnerabilities!
  340 + do {
  341 + $old_str = $str;
  342 + $str = preg_replace_callback($pattern, array($this, '_sanitize_naughty_html'), $str);
  343 + } while ($old_str !== $str);
  344 + unset($old_str);
  345 +
  346 + /*
  347 + * Sanitize naughty scripting elements
  348 + *
  349 + * Similar to above, only instead of looking for
  350 + * tags it looks for PHP and JavaScript commands
  351 + * that are disallowed. Rather than removing the
  352 + * code, it simply converts the parenthesis to entities
  353 + * rendering the code un-executable.
  354 + *
  355 + * For example: eval('some code')
  356 + * Becomes: eval&#40;'some code'&#41;
  357 + */
  358 + $str = preg_replace(
  359 + '#(alert|prompt|confirm|cmd|passthru|eval|exec|expression|system|fopen|fsockopen|file|file_get_contents|readfile|unlink)(\s*)\((.*?)\)#si',
  360 + '\\1\\2&#40;\\3&#41;',
  361 + $str
  362 + );
  363 +
  364 + // Same thing, but for "tag functions" (e.g. eval`some code`)
  365 + $str = preg_replace(
  366 + '#(alert|prompt|confirm|cmd|passthru|eval|exec|expression|system|fopen|fsockopen|file|file_get_contents|readfile|unlink)(\s*)`(.*?)`#si',
  367 + '\\1\\2&#96;\\3&#96;',
  368 + $str
  369 + );
  370 +
  371 + // Final clean up
  372 + // This adds a bit of extra precaution in case
  373 + // something got through the above filters
  374 + $str = $this->_do_never_allowed($str);
  375 +
  376 + /*
  377 + * Images are Handled in a Special Way
  378 + * - Essentially, we want to know that after all of the character
  379 + * conversion is done whether any unwanted, likely XSS, code was found.
  380 + * If not, we return TRUE, as the image is clean.
  381 + * However, if the string post-conversion does not matched the
  382 + * string post-removal of XSS, then it fails, as there was unwanted XSS
  383 + * code found and removed/changed during processing.
  384 + */
  385 + if ($is_image === true) {
  386 + return ($str === $converted_string);
  387 + }
  388 +
  389 + return $str;
  390 + }
  391 +
  392 + // --------------------------------------------------------------------
  393 +
  394 + /**
  395 + * XSS Hash
  396 + *
  397 + * Generates the XSS hash if needed and returns it.
  398 + *
  399 + * @return string XSS hash
  400 + */
  401 + public function xss_hash()
  402 + {
  403 + if ($this->_xss_hash === null) {
  404 + $rand = $this->get_random_bytes(16);
  405 + $this->_xss_hash = ($rand === false)
  406 + ? md5(uniqid(mt_rand(), true))
  407 + : bin2hex($rand);
  408 + }
  409 +
  410 + return $this->_xss_hash;
  411 + }
  412 +
  413 + // --------------------------------------------------------------------
  414 +
  415 + /**
  416 + * Get random bytes
  417 + *
  418 + * @param int $length Output length
  419 + * @return string
  420 + */
  421 + public function get_random_bytes($length)
  422 + {
  423 + if (empty($length) OR !ctype_digit((string)$length)) {
  424 + return false;
  425 + }
  426 +
  427 + if (function_exists('random_bytes')) {
  428 + try {
  429 + // The cast is required to avoid TypeError
  430 + return random_bytes((int)$length);
  431 + } catch (Exception $e) {
  432 + // If random_bytes() can't do the job, we can't either ...
  433 + // There's no point in using fallbacks.
  434 + return false;
  435 + }
  436 + }
  437 +
  438 + // Unfortunately, none of the following PRNGs is guaranteed to exist ...
  439 + if (defined('MCRYPT_DEV_URANDOM') && ($output = mcrypt_create_iv($length, MCRYPT_DEV_URANDOM)) !== false) {
  440 + return $output;
  441 + }
  442 +
  443 +
  444 + if (is_readable('/dev/urandom') && ($fp = fopen('/dev/urandom', 'rb')) !== false) {
  445 + // Try not to waste entropy ...
  446 + stream_set_chunk_size($fp, $length);
  447 + $output = fread($fp, $length);
  448 + fclose($fp);
  449 + if ($output !== false) {
  450 + return $output;
  451 + }
  452 + }
  453 +
  454 + if (function_exists('openssl_random_pseudo_bytes')) {
  455 + return openssl_random_pseudo_bytes($length);
  456 + }
  457 +
  458 + return false;
  459 + }
  460 +
  461 + // --------------------------------------------------------------------
  462 +
  463 + /**
  464 + * HTML Entities Decode
  465 + *
  466 + * A replacement for html_entity_decode()
  467 + *
  468 + * The reason we are not using html_entity_decode() by itself is because
  469 + * while it is not technically correct to leave out the semicolon
  470 + * at the end of an entity most browsers will still interpret the entity
  471 + * correctly. html_entity_decode() does not convert entities without
  472 + * semicolons, so we are left with our own little solution here. Bummer.
  473 + *
  474 + * @link https://secure.php.net/html-entity-decode
  475 + *
  476 + * @param string $str Input
  477 + * @param string $charset Character set
  478 + * @return string
  479 + */
  480 + public function entity_decode($str, $charset = null)
  481 + {
  482 + if (strpos($str, '&') === false) {
  483 + return $str;
  484 + }
  485 +
  486 + static $_entities;
  487 +
  488 + isset($charset) OR $charset = $this->charset;
  489 + isset($_entities) OR $_entities = array_map('strtolower', get_html_translation_table(HTML_ENTITIES, ENT_COMPAT | ENT_HTML5, $charset));
  490 +
  491 + do {
  492 + $str_compare = $str;
  493 +
  494 + // Decode standard entities, avoiding false positives
  495 + if (preg_match_all('/&[a-z]{2,}(?![a-z;])/i', $str, $matches)) {
  496 + $replace = array();
  497 + $matches = array_unique(array_map('strtolower', $matches[0]));
  498 + foreach ($matches as &$match) {
  499 + if (($char = array_search($match . ';', $_entities, true)) !== false) {
  500 + $replace[$match] = $char;
  501 + }
  502 + }
  503 +
  504 + $str = str_replace(array_keys($replace), array_values($replace), $str);
  505 + }
  506 +
  507 + // Decode numeric & UTF16 two byte entities
  508 + $str = html_entity_decode(
  509 + preg_replace('/(&#(?:x0*[0-9a-f]{2,5}(?![0-9a-f;])|(?:0*\d{2,4}(?![0-9;]))))/iS', '$1;', $str),
  510 + ENT_COMPAT | ENT_HTML5,
  511 + $charset
  512 + );
  513 + } while ($str_compare !== $str);
  514 + return $str;
  515 + }
  516 +
  517 + // --------------------------------------------------------------------
  518 +
  519 + /**
  520 + * Sanitize Filename
  521 + *
  522 + * @param string $str Input file name
  523 + * @param bool $relative_path Whether to preserve paths
  524 + * @return string
  525 + */
  526 + public function sanitize_filename($str, $relative_path = false)
  527 + {
  528 + $bad = $this->filename_bad_chars;
  529 +
  530 + if (!$relative_path) {
  531 + $bad[] = './';
  532 + $bad[] = '/';
  533 + }
  534 +
  535 + $str = $this->remove_invisible_characters($str, false);
  536 +
  537 + do {
  538 + $old = $str;
  539 + $str = str_replace($bad, '', $str);
  540 + } while ($old !== $str);
  541 +
  542 + return stripslashes($str);
  543 + }
  544 +
  545 + // ----------------------------------------------------------------
  546 +
  547 + /**
  548 + * Strip Image Tags
  549 + *
  550 + * @param string $str
  551 + * @return string
  552 + */
  553 + public function strip_image_tags($str)
  554 + {
  555 + return preg_replace(
  556 + array(
  557 + '#<img[\s/]+.*?src\s*=\s*(["\'])([^\\1]+?)\\1.*?\>#i',
  558 + '#<img[\s/]+.*?src\s*=\s*?(([^\s"\'=<>`]+)).*?\>#i'
  559 + ),
  560 + '\\2',
  561 + $str
  562 + );
  563 + }
  564 +
  565 + // ----------------------------------------------------------------
  566 +
  567 + /**
  568 + * URL-decode taking spaces into account
  569 + *
  570 + * @param array $matches
  571 + * @return string
  572 + */
  573 + protected function _urldecodespaces($matches)
  574 + {
  575 + $input = $matches[0];
  576 + $nospaces = preg_replace('#\s+#', '', $input);
  577 + return ($nospaces === $input)
  578 + ? $input
  579 + : rawurldecode($nospaces);
  580 + }
  581 +
  582 + // ----------------------------------------------------------------
  583 +
  584 + /**
  585 + * Compact Exploded Words
  586 + *
  587 + * Callback method for xss_clean() to remove whitespace from
  588 + * things like 'j a v a s c r i p t'.
  589 + *
  590 + * @param array $matches
  591 + * @return string
  592 + */
  593 + protected function _compact_exploded_words($matches)
  594 + {
  595 + return preg_replace('/\s+/s', '', $matches[1]) . $matches[2];
  596 + }
  597 +
  598 + // --------------------------------------------------------------------
  599 +
  600 + /**
  601 + * Sanitize Naughty HTML
  602 + *
  603 + * Callback method for xss_clean() to remove naughty HTML elements.
  604 + *
  605 + * @param array $matches
  606 + * @return string
  607 + */
  608 + protected function _sanitize_naughty_html($matches)
  609 + {
  610 + static $naughty_tags = array(
  611 + 'alert',
  612 + 'area',
  613 + 'prompt',
  614 + 'confirm',
  615 + 'applet',
  616 + 'audio',
  617 + 'basefont',
  618 + 'base',
  619 + 'behavior',
  620 + 'bgsound',
  621 + 'blink',
  622 + 'body',
  623 + 'embed',
  624 + 'expression',
  625 + 'form',
  626 + 'frameset',
  627 + 'frame',
  628 + 'head',
  629 + 'html',
  630 + 'ilayer',
  631 + 'iframe',
  632 + 'input',
  633 + 'button',
  634 + 'select',
  635 + 'isindex',
  636 + 'layer',
  637 + 'link',
  638 + 'meta',
  639 + 'keygen',
  640 + 'object',
  641 + 'plaintext',
  642 + 'style',
  643 + 'script',
  644 + 'textarea',
  645 + 'title',
  646 + 'math',
  647 + 'video',
  648 + 'svg',
  649 + 'xml',
  650 + 'xss'
  651 + );
  652 +
  653 + static $evil_attributes = array(
  654 + 'on\w+',
  655 + 'style',
  656 + 'xmlns',
  657 + 'formaction',
  658 + 'form',
  659 + 'xlink:href',
  660 + 'FSCommand',
  661 + 'seekSegmentTime'
  662 + );
  663 +
  664 + // First, escape unclosed tags
  665 + if (empty($matches['closeTag'])) {
  666 + return '&lt;' . $matches[1];
  667 + } // Is the element that we caught naughty? If so, escape it
  668 + elseif (in_array(strtolower($matches['tagName']), $naughty_tags, true)) {
  669 + return '&lt;' . $matches[1] . '&gt;';
  670 + } // For other tags, see if their attributes are "evil" and strip those
  671 + elseif (isset($matches['attributes'])) {
  672 + // We'll store the already filtered attributes here
  673 + $attributes = array();
  674 +
  675 + // Attribute-catching pattern
  676 + $attributes_pattern = '#'
  677 + . '(?<name>[^\s\042\047>/=]+)' // attribute characters
  678 + // optional attribute-value
  679 + . '(?:\s*=(?<value>[^\s\042\047=><`]+|\s*\042[^\042]*\042|\s*\047[^\047]*\047|\s*(?U:[^\s\042\047=><`]*)))' // attribute-value separator
  680 + . '#i';
  681 +
  682 + // Blacklist pattern for evil attribute names
  683 + $is_evil_pattern = '#^(' . implode('|', $evil_attributes) . ')$#i';
  684 +
  685 + // Each iteration filters a single attribute
  686 + do {
  687 + // Strip any non-alpha characters that may precede an attribute.
  688 + // Browsers often parse these incorrectly and that has been a
  689 + // of numerous XSS issues we've had.
  690 + $matches['attributes'] = preg_replace('#^[^a-z]+#i', '', $matches['attributes']);
  691 +
  692 + if (!preg_match($attributes_pattern, $matches['attributes'], $attribute, PREG_OFFSET_CAPTURE)) {
  693 + // No (valid) attribute found? Discard everything else inside the tag
  694 + break;
  695 + }
  696 +
  697 + if (
  698 + // Is it indeed an "evil" attribute?
  699 + preg_match($is_evil_pattern, $attribute['name'][0])
  700 + // Or does it have an equals sign, but no value and not quoted? Strip that too!
  701 + OR (trim($attribute['value'][0]) === '')
  702 + ) {
  703 + $attributes[] = 'xss=removed';
  704 + } else {
  705 + $attributes[] = $attribute[0][0];
  706 + }
  707 +
  708 + $matches['attributes'] = substr($matches['attributes'], $attribute[0][1] + strlen($attribute[0][0]));
  709 + } while ($matches['attributes'] !== '');
  710 +
  711 + $attributes = empty($attributes)
  712 + ? ''
  713 + : ' ' . implode(' ', $attributes);
  714 + return '<' . $matches['slash'] . $matches['tagName'] . $attributes . '>';
  715 + }
  716 +
  717 + return $matches[0];
  718 + }
  719 +
  720 + // --------------------------------------------------------------------
  721 +
  722 + /**
  723 + * JS Link Removal
  724 + *
  725 + * Callback method for xss_clean() to sanitize links.
  726 + *
  727 + * This limits the PCRE backtracks, making it more performance friendly
  728 + * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in
  729 + * PHP 5.2+ on link-heavy strings.
  730 + *
  731 + * @param array $match
  732 + * @return string
  733 + */
  734 + protected function _js_link_removal($match)
  735 + {
  736 + return str_replace(
  737 + $match[1],
  738 + preg_replace(
  739 + '#href=.*?(?:(?:alert|prompt|confirm)(?:\(|&\#40;|`|&\#96;)|javascript:|livescript:|mocha:|charset=|window\.|\(?document\)?\.|\.cookie|<script|<xss|d\s*a\s*t\s*a\s*:)#si',
  740 + '',
  741 + $this->_filter_attributes($match[1])
  742 + ),
  743 + $match[0]
  744 + );
  745 + }
  746 +
  747 + // --------------------------------------------------------------------
  748 +
  749 + /**
  750 + * JS Image Removal
  751 + *
  752 + * Callback method for xss_clean() to sanitize image tags.
  753 + *
  754 + * This limits the PCRE backtracks, making it more performance friendly
  755 + * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in
  756 + * PHP 5.2+ on image tag heavy strings.
  757 + *
  758 + * @param array $match
  759 + * @return string
  760 + */
  761 + protected function _js_img_removal($match)
  762 + {
  763 + return str_replace(
  764 + $match[1],
  765 + preg_replace(
  766 + '#src=.*?(?:(?:alert|prompt|confirm|eval)(?:\(|&\#40;|`|&\#96;)|javascript:|livescript:|mocha:|charset=|window\.|\(?document\)?\.|\.cookie|<script|<xss|base64\s*,)#si',
  767 + '',
  768 + $this->_filter_attributes($match[1])
  769 + ),
  770 + $match[0]
  771 + );
  772 + }
  773 +
  774 + // --------------------------------------------------------------------
  775 +
  776 + /**
  777 + * Attribute Conversion
  778 + *
  779 + * @param array $match
  780 + * @return string
  781 + */
  782 + protected function _convert_attribute($match)
  783 + {
  784 + return str_replace(array('>', '<', '\\'), array('&gt;', '&lt;', '\\\\'), $match[0]);
  785 + }
  786 +
  787 + // --------------------------------------------------------------------
  788 +
  789 + /**
  790 + * Filter Attributes
  791 + *
  792 + * Filters tag attributes for consistency and safety.
  793 + *
  794 + * @param string $str
  795 + * @return string
  796 + */
  797 + protected function _filter_attributes($str)
  798 + {
  799 + $out = '';
  800 + if (preg_match_all('#\s*[a-z\-]+\s*=\s*(\042|\047)([^\\1]*?)\\1#is', $str, $matches)) {
  801 + foreach ($matches[0] as $match) {
  802 + $out .= preg_replace('#/\*.*?\*/#s', '', $match);
  803 + }
  804 + }
  805 +
  806 + return $out;
  807 + }
  808 +
  809 + // --------------------------------------------------------------------
  810 +
  811 + /**
  812 + * HTML Entity Decode Callback
  813 + *
  814 + * @param array $match
  815 + * @return string
  816 + */
  817 + protected function _decode_entity($match)
  818 + {
  819 + // Protect GET variables in URLs
  820 + // 901119URL5918AMP18930PROTECT8198
  821 + $match = preg_replace('|\&([a-z\_0-9\-]+)\=([a-z\_0-9\-/]+)|i', $this->xss_hash() . '\\1=\\2', $match[0]);
  822 +
  823 + // Decode, then un-protect URL GET vars
  824 + return str_replace(
  825 + $this->xss_hash(),
  826 + '&',
  827 + $this->entity_decode($match, $this->charset)
  828 + );
  829 + }
  830 +
  831 + // --------------------------------------------------------------------
  832 +
  833 + /**
  834 + * Do Never Allowed
  835 + *
  836 + * @param string
  837 + * @return string
  838 + */
  839 + protected function _do_never_allowed($str)
  840 + {
  841 + $str = str_replace(array_keys($this->_never_allowed_str), $this->_never_allowed_str, $str);
  842 +
  843 + foreach ($this->_never_allowed_regex as $regex) {
  844 + $str = preg_replace('#' . $regex . '#is', $this->options['placeholder'], $str);
  845 + }
  846 +
  847 + return $str;
  848 + }
  849 +
  850 + /**
  851 + * Remove Invisible Characters
  852 + */
  853 + public function remove_invisible_characters($str, $url_encoded = true)
  854 + {
  855 + $non_displayables = array();
  856 +
  857 + // every control character except newline (dec 10),
  858 + // carriage return (dec 13) and horizontal tab (dec 09)
  859 + if ($url_encoded) {
  860 + $non_displayables[] = '/%0[0-8bcef]/i'; // url encoded 00-08, 11, 12, 14, 15
  861 + $non_displayables[] = '/%1[0-9a-f]/i'; // url encoded 16-31
  862 + $non_displayables[] = '/%7f/i'; // url encoded 127
  863 + }
  864 +
  865 + $non_displayables[] = '/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/S'; // 00-08, 11, 12, 14-31, 127
  866 +
  867 + do {
  868 + $str = preg_replace($non_displayables, '', $str, -1, $count);
  869 + } while ($count);
  870 +
  871 + return $str;
  872 + }
  873 +
  874 +}