Security.php 27 KB

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