Security.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866
  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. if (is_readable('/dev/urandom') && ($fp = fopen('/dev/urandom', 'rb')) !== false) {
  395. // Try not to waste entropy ...
  396. stream_set_chunk_size($fp, $length);
  397. $output = fread($fp, $length);
  398. fclose($fp);
  399. if ($output !== false) {
  400. return $output;
  401. }
  402. }
  403. if (function_exists('openssl_random_pseudo_bytes')) {
  404. return openssl_random_pseudo_bytes($length);
  405. }
  406. return false;
  407. }
  408. // --------------------------------------------------------------------
  409. /**
  410. * HTML Entities Decode
  411. *
  412. * A replacement for html_entity_decode()
  413. *
  414. * The reason we are not using html_entity_decode() by itself is because
  415. * while it is not technically correct to leave out the semicolon
  416. * at the end of an entity most browsers will still interpret the entity
  417. * correctly. html_entity_decode() does not convert entities without
  418. * semicolons, so we are left with our own little solution here. Bummer.
  419. *
  420. * @link https://secure.php.net/html-entity-decode
  421. *
  422. * @param string $str Input
  423. * @param string $charset Character set
  424. * @return string
  425. */
  426. public function entity_decode($str, $charset = null)
  427. {
  428. if (strpos($str, '&') === false) {
  429. return $str;
  430. }
  431. static $_entities;
  432. isset($charset) or $charset = $this->charset;
  433. isset($_entities) or $_entities = array_map('strtolower', get_html_translation_table(HTML_ENTITIES, ENT_COMPAT | ENT_HTML5, $charset));
  434. do {
  435. $str_compare = $str;
  436. // Decode standard entities, avoiding false positives
  437. if (preg_match_all('/&[a-z]{2,}(?![a-z;])/i', $str, $matches)) {
  438. $replace = array();
  439. $matches = array_unique(array_map('strtolower', $matches[0]));
  440. foreach ($matches as &$match) {
  441. if (($char = array_search($match . ';', $_entities, true)) !== false) {
  442. $replace[$match] = $char;
  443. }
  444. }
  445. $str = str_replace(array_keys($replace), array_values($replace), $str);
  446. }
  447. // Decode numeric & UTF16 two byte entities
  448. $str = html_entity_decode(
  449. preg_replace('/(&#(?:x0*[0-9a-f]{2,5}(?![0-9a-f;])|(?:0*\d{2,4}(?![0-9;]))))/iS', '$1;', $str),
  450. ENT_COMPAT | ENT_HTML5,
  451. $charset
  452. );
  453. } while ($str_compare !== $str);
  454. return $str;
  455. }
  456. // --------------------------------------------------------------------
  457. /**
  458. * Sanitize Filename
  459. *
  460. * @param string $str Input file name
  461. * @param bool $relative_path Whether to preserve paths
  462. * @return string
  463. */
  464. public function sanitize_filename($str, $relative_path = false)
  465. {
  466. $bad = $this->filename_bad_chars;
  467. if (!$relative_path) {
  468. $bad[] = './';
  469. $bad[] = '/';
  470. }
  471. $str = $this->remove_invisible_characters($str, false);
  472. do {
  473. $old = $str;
  474. $str = str_replace($bad, '', $str);
  475. } while ($old !== $str);
  476. return stripslashes($str);
  477. }
  478. // ----------------------------------------------------------------
  479. /**
  480. * Strip Image Tags
  481. *
  482. * @param string $str
  483. * @return string
  484. */
  485. public function strip_image_tags($str)
  486. {
  487. return preg_replace(
  488. array(
  489. '#<img[\s/]+.*?src\s*=\s*(["\'])([^\\1]+?)\\1.*?\>#i',
  490. '#<img[\s/]+.*?src\s*=\s*?(([^\s"\'=<>`]+)).*?\>#i'
  491. ),
  492. '\\2',
  493. $str
  494. );
  495. }
  496. // ----------------------------------------------------------------
  497. /**
  498. * URL-decode taking spaces into account
  499. *
  500. * @param array $matches
  501. * @return string
  502. */
  503. protected function _urldecodespaces($matches)
  504. {
  505. $input = $matches[0];
  506. $nospaces = preg_replace('#\s+#', '', $input);
  507. return ($nospaces === $input)
  508. ? $input
  509. : rawurldecode($nospaces);
  510. }
  511. // ----------------------------------------------------------------
  512. /**
  513. * Compact Exploded Words
  514. *
  515. * Callback method for xss_clean() to remove whitespace from
  516. * things like 'j a v a s c r i p t'.
  517. *
  518. * @param array $matches
  519. * @return string
  520. */
  521. protected function _compact_exploded_words($matches)
  522. {
  523. return preg_replace('/\s+/s', '', $matches[1]) . $matches[2];
  524. }
  525. // --------------------------------------------------------------------
  526. /**
  527. * Sanitize Naughty HTML
  528. *
  529. * Callback method for xss_clean() to remove naughty HTML elements.
  530. *
  531. * @param array $matches
  532. * @return string
  533. */
  534. protected function _sanitize_naughty_html($matches)
  535. {
  536. static $naughty_tags = array(
  537. 'alert',
  538. 'area',
  539. 'prompt',
  540. 'confirm',
  541. 'applet',
  542. 'audio',
  543. 'basefont',
  544. 'base',
  545. 'behavior',
  546. 'bgsound',
  547. 'blink',
  548. 'body',
  549. 'embed',
  550. 'expression',
  551. 'form',
  552. 'frameset',
  553. 'frame',
  554. 'head',
  555. 'html',
  556. 'ilayer',
  557. 'iframe',
  558. 'input',
  559. 'button',
  560. 'select',
  561. 'isindex',
  562. 'layer',
  563. 'link',
  564. 'meta',
  565. 'keygen',
  566. 'object',
  567. 'plaintext',
  568. 'style',
  569. 'script',
  570. 'textarea',
  571. 'title',
  572. 'math',
  573. 'video',
  574. 'svg',
  575. 'xml',
  576. 'xss'
  577. );
  578. static $evil_attributes = array(
  579. 'on\w+',
  580. 'style',
  581. 'xmlns',
  582. 'formaction',
  583. 'form',
  584. 'xlink:href',
  585. 'FSCommand',
  586. 'seekSegmentTime'
  587. );
  588. // First, escape unclosed tags
  589. if (empty($matches['closeTag'])) {
  590. return '&lt;' . $matches[1];
  591. } // Is the element that we caught naughty? If so, escape it
  592. elseif (in_array(strtolower($matches['tagName']), $naughty_tags, true)) {
  593. return '&lt;' . $matches[1] . '&gt;';
  594. } // For other tags, see if their attributes are "evil" and strip those
  595. elseif (isset($matches['attributes'])) {
  596. // We'll store the already filtered attributes here
  597. $attributes = array();
  598. // Attribute-catching pattern
  599. $attributes_pattern = '#'
  600. . '(?<name>[^\s\042\047>/=]+)' // attribute characters
  601. // optional attribute-value
  602. . '(?:\s*=(?<value>[^\s\042\047=><`]+|\s*\042[^\042]*\042|\s*\047[^\047]*\047|\s*(?U:[^\s\042\047=><`]*)))' // attribute-value separator
  603. . '#i';
  604. // Blacklist pattern for evil attribute names
  605. $is_evil_pattern = '#^(' . implode('|', $evil_attributes) . ')$#i';
  606. // Each iteration filters a single attribute
  607. do {
  608. // Strip any non-alpha characters that may precede an attribute.
  609. // Browsers often parse these incorrectly and that has been a
  610. // of numerous XSS issues we've had.
  611. $matches['attributes'] = preg_replace('#^[^a-z]+#i', '', $matches['attributes']);
  612. if (!preg_match($attributes_pattern, $matches['attributes'], $attribute, PREG_OFFSET_CAPTURE)) {
  613. // No (valid) attribute found? Discard everything else inside the tag
  614. break;
  615. }
  616. if (
  617. // Is it indeed an "evil" attribute?
  618. preg_match($is_evil_pattern, $attribute['name'][0])
  619. // Or does it have an equals sign, but no value and not quoted? Strip that too!
  620. or (trim($attribute['value'][0]) === '')
  621. ) {
  622. $attributes[] = 'xss=removed';
  623. } else {
  624. $attributes[] = $attribute[0][0];
  625. }
  626. $matches['attributes'] = substr($matches['attributes'], $attribute[0][1] + strlen($attribute[0][0]));
  627. } while ($matches['attributes'] !== '');
  628. $attributes = empty($attributes)
  629. ? ''
  630. : ' ' . implode(' ', $attributes);
  631. return '<' . $matches['slash'] . $matches['tagName'] . $attributes . '>';
  632. }
  633. return $matches[0];
  634. }
  635. // --------------------------------------------------------------------
  636. /**
  637. * JS Link Removal
  638. *
  639. * Callback method for xss_clean() to sanitize links.
  640. *
  641. * This limits the PCRE backtracks, making it more performance friendly
  642. * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in
  643. * PHP 5.2+ on link-heavy strings.
  644. *
  645. * @param array $match
  646. * @return string
  647. */
  648. protected function _js_link_removal($match)
  649. {
  650. return str_replace(
  651. $match[1],
  652. preg_replace(
  653. '#href=.*?(?:(?:alert|prompt|confirm)(?:\(|&\#40;|`|&\#96;)|javascript:|livescript:|mocha:|charset=|window\.|\(?document\)?\.|\.cookie|<script|<xss|d\s*a\s*t\s*a\s*:)#si',
  654. '',
  655. $this->_filter_attributes($match[1])
  656. ),
  657. $match[0]
  658. );
  659. }
  660. // --------------------------------------------------------------------
  661. /**
  662. * JS Image Removal
  663. *
  664. * Callback method for xss_clean() to sanitize image tags.
  665. *
  666. * This limits the PCRE backtracks, making it more performance friendly
  667. * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in
  668. * PHP 5.2+ on image tag heavy strings.
  669. *
  670. * @param array $match
  671. * @return string
  672. */
  673. protected function _js_img_removal($match)
  674. {
  675. return str_replace(
  676. $match[1],
  677. preg_replace(
  678. '#src=.*?(?:(?:alert|prompt|confirm|eval)(?:\(|&\#40;|`|&\#96;)|javascript:|livescript:|mocha:|charset=|window\.|\(?document\)?\.|\.cookie|<script|<xss|base64\s*,)#si',
  679. '',
  680. $this->_filter_attributes($match[1])
  681. ),
  682. $match[0]
  683. );
  684. }
  685. // --------------------------------------------------------------------
  686. /**
  687. * Attribute Conversion
  688. *
  689. * @param array $match
  690. * @return string
  691. */
  692. protected function _convert_attribute($match)
  693. {
  694. return str_replace(array('>', '<', '\\'), array('&gt;', '&lt;', '\\\\'), $match[0]);
  695. }
  696. // --------------------------------------------------------------------
  697. /**
  698. * Filter Attributes
  699. *
  700. * Filters tag attributes for consistency and safety.
  701. *
  702. * @param string $str
  703. * @return string
  704. */
  705. protected function _filter_attributes($str)
  706. {
  707. $out = '';
  708. if (preg_match_all('#\s*[a-z\-]+\s*=\s*(\042|\047)([^\\1]*?)\\1#is', $str, $matches)) {
  709. foreach ($matches[0] as $match) {
  710. $out .= preg_replace('#/\*.*?\*/#s', '', $match);
  711. }
  712. }
  713. return $out;
  714. }
  715. // --------------------------------------------------------------------
  716. /**
  717. * HTML Entity Decode Callback
  718. *
  719. * @param array $match
  720. * @return string
  721. */
  722. protected function _decode_entity($match)
  723. {
  724. // Protect GET variables in URLs
  725. // 901119URL5918AMP18930PROTECT8198
  726. $match = preg_replace('|\&([a-z\_0-9\-]+)\=([a-z\_0-9\-/]+)|i', $this->xss_hash() . '\\1=\\2', $match[0]);
  727. // Decode, then un-protect URL GET vars
  728. return str_replace(
  729. $this->xss_hash(),
  730. '&',
  731. $this->entity_decode($match, $this->charset)
  732. );
  733. }
  734. // --------------------------------------------------------------------
  735. /**
  736. * Do Never Allowed
  737. *
  738. * @param string
  739. * @return string
  740. */
  741. protected function _do_never_allowed($str)
  742. {
  743. $str = str_replace(array_keys($this->_never_allowed_str), $this->_never_allowed_str, $str);
  744. foreach ($this->_never_allowed_regex as $regex) {
  745. $str = preg_replace('#' . $regex . '#is', $this->options['placeholder'], $str);
  746. }
  747. return $str;
  748. }
  749. /**
  750. * Remove Invisible Characters
  751. */
  752. public function remove_invisible_characters($str, $url_encoded = true)
  753. {
  754. $non_displayables = array();
  755. // every control character except newline (dec 10),
  756. // carriage return (dec 13) and horizontal tab (dec 09)
  757. if ($url_encoded) {
  758. $non_displayables[] = '/%0[0-8bcef]/i'; // url encoded 00-08, 11, 12, 14, 15
  759. $non_displayables[] = '/%1[0-9a-f]/i'; // url encoded 16-31
  760. $non_displayables[] = '/%7f/i'; // url encoded 127
  761. }
  762. $non_displayables[] = '/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/S'; // 00-08, 11, 12, 14-31, 127
  763. do {
  764. $str = preg_replace($non_displayables, '', $str, -1, $count);
  765. } while ($count);
  766. return $str;
  767. }
  768. }