PageRenderTime 49ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/application/protected/extensions/vendors/Codeigniter/CI_Security.php

https://bitbucket.org/dinhtrung/yiicorecms/
PHP | 752 lines | 648 code | 15 blank | 89 comment | 2 complexity | 45d587d5bca05637ebcef39ba07356da MD5 | raw file
Possible License(s): GPL-3.0, BSD-3-Clause, CC0-1.0, BSD-2-Clause, GPL-2.0, LGPL-2.1, LGPL-3.0
  1. <?php
  2. /**
  3. * Changes:
  4. * 1) Removed $_csrf_hash,$_csrf_expire,$_csrf_token_name,$_csrf_cookie_name
  5. * 2) Cleaned the constructor.
  6. * 3) removed csrf_verify(), csrf_set_cookie(), csrf_show_error(), get_csrf_hash(), get_csrf_token_name()
  7. * 4) removed log_message() and config_item();
  8. * 5) removed _csrf_set_hash();
  9. * 6) added remove_invisible_characters() and clean_file()
  10. **/
  11. /**
  12. * CodeIgniter
  13. *
  14. * An open source application development framework for PHP 5.1.6 or newer
  15. *
  16. * @package CodeIgniter
  17. * @author ExpressionEngine Dev Team
  18. * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
  19. * @license http://codeigniter.com/user_guide/license.html
  20. * @link http://codeigniter.com
  21. * @since Version 1.0
  22. * @filesource
  23. */
  24. // ------------------------------------------------------------------------
  25. /**
  26. * Security Class
  27. *
  28. * @package CodeIgniter
  29. * @subpackage Libraries
  30. * @category Security
  31. * @author ExpressionEngine Dev Team
  32. * @link http://codeigniter.com/user_guide/libraries/security.html
  33. */
  34. class CI_Security {
  35. protected $_xss_hash = '';
  36. /* never allowed, string replacement */
  37. protected $_never_allowed_str = array(
  38. 'document.cookie' => '[removed]',
  39. 'document.write' => '[removed]',
  40. '.parentNode' => '[removed]',
  41. '.innerHTML' => '[removed]',
  42. 'window.location' => '[removed]',
  43. '-moz-binding' => '[removed]',
  44. '<!--' => '&lt;!--',
  45. '-->' => '--&gt;',
  46. '<![CDATA[' => '&lt;![CDATA['
  47. );
  48. /* never allowed, regex replacement */
  49. protected $_never_allowed_regex = array(
  50. "javascript\s*:" => '[removed]',
  51. "expression\s*(\(|&\#40;)" => '[removed]', // CSS and IE
  52. "vbscript\s*:" => '[removed]', // IE, surprise!
  53. "Redirect\s+302" => '[removed]'
  54. );
  55. /**
  56. * Constructor
  57. */
  58. public function __construct(){}
  59. // --------------------------------------------------------------------
  60. /**
  61. * XSS Clean
  62. *
  63. * Sanitizes data so that Cross Site Scripting Hacks can be
  64. * prevented. This function does a fair amount of work but
  65. * it is extremely thorough, designed to prevent even the
  66. * most obscure XSS attempts. Nothing is ever 100% foolproof,
  67. * of course, but I haven't been able to get anything passed
  68. * the filter.
  69. *
  70. * Note: This function should only be used to deal with data
  71. * upon submission. It's not something that should
  72. * be used for general runtime processing.
  73. *
  74. * This function was based in part on some code and ideas I
  75. * got from Bitflux: http://channel.bitflux.ch/wiki/XSS_Prevention
  76. *
  77. * To help develop this script I used this great list of
  78. * vulnerabilities along with a few other hacks I've
  79. * harvested from examining vulnerabilities in other programs:
  80. * http://ha.ckers.org/xss.html
  81. *
  82. * @param mixed string or array
  83. * @return string
  84. */
  85. public function xss_clean($str, $is_image = FALSE)
  86. {
  87. /*
  88. * Is the string an array?
  89. *
  90. */
  91. if (is_array($str))
  92. {
  93. while (list($key) = each($str))
  94. {
  95. $str[$key] = $this->xss_clean($str[$key]);
  96. }
  97. return $str;
  98. }
  99. /*
  100. * Remove Invisible Characters
  101. */
  102. $str = $this->remove_invisible_characters($str);
  103. // Validate Entities in URLs
  104. $str = $this->_validate_entities($str);
  105. /*
  106. * URL Decode
  107. *
  108. * Just in case stuff like this is submitted:
  109. *
  110. * <a href="http://%77%77%77%2E%67%6F%6F%67%6C%65%2E%63%6F%6D">Google</a>
  111. *
  112. * Note: Use rawurldecode() so it does not remove plus signs
  113. *
  114. */
  115. $str = rawurldecode($str);
  116. /*
  117. * Convert character entities to ASCII
  118. *
  119. * This permits our tests below to work reliably.
  120. * We only convert entities that are within tags since
  121. * these are the ones that will pose security problems.
  122. *
  123. */
  124. $str = preg_replace_callback("/[a-z]+=([\'\"]).*?\\1/si", array($this, '_convert_attribute'), $str);
  125. $str = preg_replace_callback("/<\w+.*?(?=>|<|$)/si", array($this, '_decode_entity'), $str);
  126. /*
  127. * Remove Invisible Characters Again!
  128. */
  129. $str = $this->remove_invisible_characters($str);
  130. /*
  131. * Convert all tabs to spaces
  132. *
  133. * This prevents strings like this: ja vascript
  134. * NOTE: we deal with spaces between characters later.
  135. * NOTE: preg_replace was found to be amazingly slow here on
  136. * large blocks of data, so we use str_replace.
  137. */
  138. if (strpos($str, "\t") !== FALSE)
  139. {
  140. $str = str_replace("\t", ' ', $str);
  141. }
  142. /*
  143. * Capture converted string for later comparison
  144. */
  145. $converted_string = $str;
  146. // Remove Strings that are never allowed
  147. $str = $this->_do_never_allowed($str);
  148. /*
  149. * Makes PHP tags safe
  150. *
  151. * Note: XML tags are inadvertently replaced too:
  152. *
  153. * <?xml
  154. *
  155. * But it doesn't seem to pose a problem.
  156. */
  157. if ($is_image === TRUE)
  158. {
  159. // Images have a tendency to have the PHP short opening and
  160. // closing tags every so often so we skip those and only
  161. // do the long opening tags.
  162. $str = preg_replace('/<\?(php)/i', "&lt;?\\1", $str);
  163. }
  164. else
  165. {
  166. $str = str_replace(array('<?', '?'.'>'), array('&lt;?', '?&gt;'), $str);
  167. }
  168. /*
  169. * Compact any exploded words
  170. *
  171. * This corrects words like: j a v a s c r i p t
  172. * These words are compacted back to their correct state.
  173. */
  174. $words = array(
  175. 'javascript', 'expression', 'vbscript', 'script',
  176. 'applet', 'alert', 'document', 'write', 'cookie', 'window'
  177. );
  178. foreach ($words as $word)
  179. {
  180. $temp = '';
  181. for ($i = 0, $wordlen = strlen($word); $i < $wordlen; $i++)
  182. {
  183. $temp .= substr($word, $i, 1)."\s*";
  184. }
  185. // We only want to do this when it is followed by a non-word character
  186. // That way valid stuff like "dealer to" does not become "dealerto"
  187. $str = preg_replace_callback('#('.substr($temp, 0, -3).')(\W)#is', array($this, '_compact_exploded_words'), $str);
  188. }
  189. /*
  190. * Remove disallowed Javascript in links or img tags
  191. * We used to do some version comparisons and use of stripos for PHP5,
  192. * but it is dog slow compared to these simplified non-capturing
  193. * preg_match(), especially if the pattern exists in the string
  194. */
  195. do
  196. {
  197. $original = $str;
  198. if (preg_match("/<a/i", $str))
  199. {
  200. $str = preg_replace_callback("#<a\s+([^>]*?)(>|$)#si", array($this, '_js_link_removal'), $str);
  201. }
  202. if (preg_match("/<img/i", $str))
  203. {
  204. $str = preg_replace_callback("#<img\s+([^>]*?)(\s?/?>|$)#si", array($this, '_js_img_removal'), $str);
  205. }
  206. if (preg_match("/script/i", $str) OR preg_match("/xss/i", $str))
  207. {
  208. $str = preg_replace("#<(/*)(script|xss)(.*?)\>#si", '[removed]', $str);
  209. }
  210. }
  211. while($original != $str);
  212. unset($original);
  213. // Remove evil attributes such as style, onclick and xmlns
  214. $str = $this->_remove_evil_attributes($str, $is_image);
  215. /*
  216. * Sanitize naughty HTML elements
  217. *
  218. * If a tag containing any of the words in the list
  219. * below is found, the tag gets converted to entities.
  220. *
  221. * So this: <blink>
  222. * Becomes: &lt;blink&gt;
  223. */
  224. $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';
  225. $str = preg_replace_callback('#<(/*\s*)('.$naughty.')([^><]*)([><]*)#is', array($this, '_sanitize_naughty_html'), $str);
  226. /*
  227. * Sanitize naughty scripting elements
  228. *
  229. * Similar to above, only instead of looking for
  230. * tags it looks for PHP and JavaScript commands
  231. * that are disallowed. Rather than removing the
  232. * code, it simply converts the parenthesis to entities
  233. * rendering the code un-executable.
  234. *
  235. * For example: eval('some code')
  236. * Becomes: eval&#40;'some code'&#41;
  237. */
  238. $str = preg_replace('#(alert|cmd|passthru|eval|exec|expression|system|fopen|fsockopen|file|file_get_contents|readfile|unlink)(\s*)\((.*?)\)#si', "\\1\\2&#40;\\3&#41;", $str);
  239. // Final clean up
  240. // This adds a bit of extra precaution in case
  241. // something got through the above filters
  242. $str = $this->_do_never_allowed($str);
  243. /*
  244. * Images are Handled in a Special Way
  245. * - Essentially, we want to know that after all of the character
  246. * conversion is done whether any unwanted, likely XSS, code was found.
  247. * If not, we return TRUE, as the image is clean.
  248. * However, if the string post-conversion does not matched the
  249. * string post-removal of XSS, then it fails, as there was unwanted XSS
  250. * code found and removed/changed during processing.
  251. */
  252. if ($is_image === TRUE)
  253. {
  254. return ($str == $converted_string) ? TRUE: FALSE;
  255. }
  256. return $str;
  257. }
  258. // --------------------------------------------------------------------
  259. /**
  260. * Random Hash for protecting URLs
  261. *
  262. * @return string
  263. */
  264. public function xss_hash()
  265. {
  266. if ($this->_xss_hash == '')
  267. {
  268. if (phpversion() >= 4.2)
  269. {
  270. mt_srand();
  271. }
  272. else
  273. {
  274. mt_srand(hexdec(substr(md5(microtime()), -8)) & 0x7fffffff);
  275. }
  276. $this->_xss_hash = md5(time() + mt_rand(0, 1999999999));
  277. }
  278. return $this->_xss_hash;
  279. }
  280. // --------------------------------------------------------------------
  281. /**
  282. * HTML Entities Decode
  283. *
  284. * This function is a replacement for html_entity_decode()
  285. *
  286. * In some versions of PHP the native function does not work
  287. * when UTF-8 is the specified character set, so this gives us
  288. * a work-around. More info here:
  289. * http://bugs.php.net/bug.php?id=25670
  290. *
  291. * NOTE: html_entity_decode() has a bug in some PHP versions when UTF-8 is the
  292. * character set, and the PHP developers said they were not back porting the
  293. * fix to versions other than PHP 5.x.
  294. *
  295. * @param string
  296. * @param string
  297. * @return string
  298. */
  299. public function entity_decode($str, $charset='UTF-8')
  300. {
  301. if (stristr($str, '&') === FALSE) return $str;
  302. // The reason we are not using html_entity_decode() by itself is because
  303. // while it is not technically correct to leave out the semicolon
  304. // at the end of an entity most browsers will still interpret the entity
  305. // correctly. html_entity_decode() does not convert entities without
  306. // semicolons, so we are left with our own little solution here. Bummer.
  307. if (function_exists('html_entity_decode') &&
  308. (strtolower($charset) != 'utf-8'))
  309. {
  310. $str = html_entity_decode($str, ENT_COMPAT, $charset);
  311. $str = preg_replace('~&#x(0*[0-9a-f]{2,5})~ei', 'chr(hexdec("\\1"))', $str);
  312. return preg_replace('~&#([0-9]{2,4})~e', 'chr(\\1)', $str);
  313. }
  314. // Numeric Entities
  315. $str = preg_replace('~&#x(0*[0-9a-f]{2,5});{0,1}~ei', 'chr(hexdec("\\1"))', $str);
  316. $str = preg_replace('~&#([0-9]{2,4});{0,1}~e', 'chr(\\1)', $str);
  317. // Literal Entities - Slightly slow so we do another check
  318. if (stristr($str, '&') === FALSE)
  319. {
  320. $str = strtr($str, array_flip(get_html_translation_table(HTML_ENTITIES)));
  321. }
  322. return $str;
  323. }
  324. // --------------------------------------------------------------------
  325. /**
  326. * Filename Security
  327. *
  328. * @param string
  329. * @return string
  330. */
  331. public function sanitize_filename($str, $relative_path = FALSE)
  332. {
  333. $bad = array(
  334. "../",
  335. "<!--",
  336. "-->",
  337. "<",
  338. ">",
  339. "'",
  340. '"',
  341. '&',
  342. '$',
  343. '#',
  344. '{',
  345. '}',
  346. '[',
  347. ']',
  348. '=',
  349. ';',
  350. '?',
  351. "%20",
  352. "%22",
  353. "%3c", // <
  354. "%253c", // <
  355. "%3e", // >
  356. "%0e", // >
  357. "%28", // (
  358. "%29", // )
  359. "%2528", // (
  360. "%26", // &
  361. "%24", // $
  362. "%3f", // ?
  363. "%3b", // ;
  364. "%3d" // =
  365. );
  366. if ( ! $relative_path)
  367. {
  368. $bad[] = './';
  369. $bad[] = '/';
  370. }
  371. $str = $this->remove_invisible_characters($str, FALSE);
  372. return stripslashes(str_replace($bad, '', $str));
  373. }
  374. // ----------------------------------------------------------------
  375. /**
  376. * Compact Exploded Words
  377. *
  378. * Callback function for xss_clean() to remove whitespace from
  379. * things like j a v a s c r i p t
  380. *
  381. * @param type
  382. * @return type
  383. */
  384. protected function _compact_exploded_words($matches)
  385. {
  386. return preg_replace('/\s+/s', '', $matches[1]).$matches[2];
  387. }
  388. // --------------------------------------------------------------------
  389. /*
  390. * Remove Evil HTML Attributes (like evenhandlers and style)
  391. *
  392. * It removes the evil attribute and either:
  393. * - Everything up until a space
  394. * For example, everything between the pipes:
  395. * <a |style=document.write('hello');alert('world');| class=link>
  396. * - Everything inside the quotes
  397. * For example, everything between the pipes:
  398. * <a |style="document.write('hello'); alert('world');"| class="link">
  399. *
  400. * @param string $str The string to check
  401. * @param boolean $is_image TRUE if this is an image
  402. * @return string The string with the evil attributes removed
  403. */
  404. protected function _remove_evil_attributes($str, $is_image)
  405. {
  406. // All javascript event handlers (e.g. onload, onclick, onmouseover), style, and xmlns
  407. $evil_attributes = array('on\w*', 'style', 'xmlns');
  408. if ($is_image === TRUE)
  409. {
  410. /*
  411. * Adobe Photoshop puts XML metadata into JFIF images,
  412. * including namespacing, so we have to allow this for images.
  413. */
  414. unset($evil_attributes[array_search('xmlns', $evil_attributes)]);
  415. }
  416. do {
  417. $str = preg_replace(
  418. "#<(/?[^><]+?)([^A-Za-z\-])(".implode('|', $evil_attributes).")(\s*=\s*)([\"][^>]*?[\"]|[\'][^>]*?[\']|[^>]*?)([\s><])([><]*)#i",
  419. "<$1$6",
  420. $str, -1, $count
  421. );
  422. } while ($count);
  423. return $str;
  424. }
  425. // --------------------------------------------------------------------
  426. /**
  427. * Sanitize Naughty HTML
  428. *
  429. * Callback function for xss_clean() to remove naughty HTML elements
  430. *
  431. * @param array
  432. * @return string
  433. */
  434. protected function _sanitize_naughty_html($matches)
  435. {
  436. // encode opening brace
  437. $str = '&lt;'.$matches[1].$matches[2].$matches[3];
  438. // encode captured opening or closing brace to prevent recursive vectors
  439. $str .= str_replace(array('>', '<'), array('&gt;', '&lt;'),
  440. $matches[4]);
  441. return $str;
  442. }
  443. // --------------------------------------------------------------------
  444. /**
  445. * JS Link Removal
  446. *
  447. * Callback function for xss_clean() to sanitize links
  448. * This limits the PCRE backtracks, making it more performance friendly
  449. * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in
  450. * PHP 5.2+ on link-heavy strings
  451. *
  452. * @param array
  453. * @return string
  454. */
  455. protected function _js_link_removal($match)
  456. {
  457. $attributes = $this->_filter_attributes(str_replace(array('<', '>'), '', $match[1]));
  458. return str_replace($match[1], preg_replace("#href=.*?(alert\(|alert&\#40;|javascript\:|livescript\:|mocha\:|charset\=|window\.|document\.|\.cookie|<script|<xss|base64\s*,)#si", "", $attributes), $match[0]);
  459. }
  460. // --------------------------------------------------------------------
  461. /**
  462. * JS Image Removal
  463. *
  464. * Callback function for xss_clean() to sanitize image tags
  465. * This limits the PCRE backtracks, making it more performance friendly
  466. * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in
  467. * PHP 5.2+ on image tag heavy strings
  468. *
  469. * @param array
  470. * @return string
  471. */
  472. protected function _js_img_removal($match)
  473. {
  474. $attributes = $this->_filter_attributes(str_replace(array('<', '>'), '', $match[1]));
  475. return str_replace($match[1], preg_replace("#src=.*?(alert\(|alert&\#40;|javascript\:|livescript\:|mocha\:|charset\=|window\.|document\.|\.cookie|<script|<xss|base64\s*,)#si", "", $attributes), $match[0]);
  476. }
  477. // --------------------------------------------------------------------
  478. /**
  479. * Attribute Conversion
  480. *
  481. * Used as a callback for XSS Clean
  482. *
  483. * @param array
  484. * @return string
  485. */
  486. protected function _convert_attribute($match)
  487. {
  488. return str_replace(array('>', '<', '\\'), array('&gt;', '&lt;', '\\\\'), $match[0]);
  489. }
  490. // --------------------------------------------------------------------
  491. /**
  492. * Filter Attributes
  493. *
  494. * Filters tag attributes for consistency and safety
  495. *
  496. * @param string
  497. * @return string
  498. */
  499. protected function _filter_attributes($str)
  500. {
  501. $out = '';
  502. if (preg_match_all('#\s*[a-z\-]+\s*=\s*(\042|\047)([^\\1]*?)\\1#is', $str, $matches))
  503. {
  504. foreach ($matches[0] as $match)
  505. {
  506. $out .= preg_replace("#/\*.*?\*/#s", '', $match);
  507. }
  508. }
  509. return $out;
  510. }
  511. // --------------------------------------------------------------------
  512. /**
  513. * HTML Entity Decode Callback
  514. *
  515. * Used as a callback for XSS Clean
  516. *
  517. * @param array
  518. * @return string
  519. */
  520. protected function _decode_entity($match)
  521. {
  522. return $this->entity_decode($match[0], strtoupper(Yii::app()->charset));
  523. }
  524. // --------------------------------------------------------------------
  525. /**
  526. * Validate URL entities
  527. *
  528. * Called by xss_clean()
  529. *
  530. * @param string
  531. * @return string
  532. */
  533. protected function _validate_entities($str)
  534. {
  535. /*
  536. * Protect GET variables in URLs
  537. */
  538. // 901119URL5918AMP18930PROTECT8198
  539. $str = preg_replace('|\&([a-z\_0-9\-]+)\=([a-z\_0-9\-]+)|i', $this->xss_hash()."\\1=\\2", $str);
  540. /*
  541. * Validate standard character entities
  542. *
  543. * Add a semicolon if missing. We do this to enable
  544. * the conversion of entities to ASCII later.
  545. *
  546. */
  547. $str = preg_replace('#(&\#?[0-9a-z]{2,})([\x00-\x20])*;?#i', "\\1;\\2", $str);
  548. /*
  549. * Validate UTF16 two byte encoding (x00)
  550. *
  551. * Just as above, adds a semicolon if missing.
  552. *
  553. */
  554. $str = preg_replace('#(&\#x?)([0-9A-F]+);?#i',"\\1\\2;",$str);
  555. /*
  556. * Un-Protect GET variables in URLs
  557. */
  558. $str = str_replace($this->xss_hash(), '&', $str);
  559. return $str;
  560. }
  561. // ----------------------------------------------------------------------
  562. /**
  563. * Do Never Allowed
  564. *
  565. * A utility function for xss_clean()
  566. *
  567. * @param string
  568. * @return string
  569. */
  570. protected function _do_never_allowed($str)
  571. {
  572. foreach ($this->_never_allowed_str as $key => $val)
  573. {
  574. $str = str_replace($key, $val, $str);
  575. }
  576. foreach ($this->_never_allowed_regex as $key => $val)
  577. {
  578. $str = preg_replace("#".$key."#i", $val, $str);
  579. }
  580. return $str;
  581. }
  582. // ----------------------------------------------------------------------
  583. /**
  584. * Remove Invisible Characters
  585. *
  586. * This prevents sandwiching null characters
  587. * between ascii characters, like Java\0script.
  588. *
  589. * @access public
  590. * @param string
  591. * @return string
  592. */
  593. public function remove_invisible_characters($str, $url_encoded = TRUE)
  594. {
  595. $non_displayables = array();
  596. // every control character except newline (dec 10)
  597. // carriage return (dec 13), and horizontal tab (dec 09)
  598. if ($url_encoded)
  599. {
  600. $non_displayables[] = '/%0[0-8bcef]/'; // url encoded 00-08, 11, 12, 14, 15
  601. $non_displayables[] = '/%1[0-9a-f]/'; // url encoded 16-31
  602. }
  603. $non_displayables[] = '/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/S'; // 00-08, 11, 12, 14-31, 127
  604. do
  605. {
  606. $str = preg_replace($non_displayables, '', $str, -1, $count);
  607. }
  608. while ($count);
  609. return $str;
  610. }
  611. // ----------------------------------------------------------------------
  612. /**
  613. * Runs the file through the XSS clean function
  614. *
  615. * This prevents people from embedding malicious code in their files.
  616. * I'm not sure that it won't negatively affect certain files in unexpected ways,
  617. * but so far I haven't found that it causes trouble.
  618. *
  619. * @return void
  620. */
  621. public function clean_file($file)
  622. {
  623. if (filesize($file) == 0)
  624. {
  625. return FALSE;
  626. }
  627. if (function_exists('memory_get_usage') && memory_get_usage() && ini_get('memory_limit') != '')
  628. {
  629. $current = ini_get('memory_limit') * 1024 * 1024;
  630. $newMemory = number_format(ceil(filesize($file) + $current), 0, '.', '');
  631. ini_set('memory_limit', $newMemory); // When an integer is used, the value is measured in bytes. - PHP.net
  632. }
  633. if (function_exists('getimagesize') && @getimagesize($file) !== FALSE)
  634. {
  635. if (($file = @fopen($file, 'rb')) === FALSE) // "b" to force binary
  636. {
  637. return FALSE; // Couldn't open the file, return FALSE
  638. }
  639. $openingBytes = fread($file, 256);
  640. fclose($file);
  641. if(!preg_match('/<(a|body|head|html|img|plaintext|pre|script|table|title)[\s>]/i', $openingBytes))
  642. {
  643. return TRUE; // its an image, no "triggers" detected in the first 256 bytes, we're good
  644. }
  645. }
  646. if (($data = @file_get_contents($file)) === FALSE)
  647. {
  648. return FALSE;
  649. }
  650. return $this->xss_clean($data, TRUE);
  651. }
  652. }