PageRenderTime 56ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/system/core/Security.php

https://github.com/coderkid/No-CMS
PHP | 907 lines | 470 code | 86 blank | 351 comment | 18 complexity | 925125cdd29a2f76c2f63fa2de71ae80 MD5 | raw file
Possible License(s): GPL-3.0, LGPL-2.1, MPL-2.0-no-copyleft-exception, GPL-2.0
  1. <?php
  2. /**
  3. * CodeIgniter
  4. *
  5. * An open source application development framework for PHP 5.2.4 or newer
  6. *
  7. * NOTICE OF LICENSE
  8. *
  9. * Licensed under the Open Software License version 3.0
  10. *
  11. * This source file is subject to the Open Software License (OSL 3.0) that is
  12. * bundled with this package in the files license.txt / license.rst. It is
  13. * also available through the world wide web at this URL:
  14. * http://opensource.org/licenses/OSL-3.0
  15. * If you did not receive a copy of the license and are unable to obtain it
  16. * through the world wide web, please send an email to
  17. * licensing@ellislab.com so we can send you a copy immediately.
  18. *
  19. * @package CodeIgniter
  20. * @author EllisLab Dev Team
  21. * @copyright Copyright (c) 2008 - 2013, EllisLab, Inc. (http://ellislab.com/)
  22. * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
  23. * @link http://codeigniter.com
  24. * @since Version 1.0
  25. * @filesource
  26. */
  27. defined('BASEPATH') OR exit('No direct script access allowed');
  28. /**
  29. * Security Class
  30. *
  31. * @package CodeIgniter
  32. * @subpackage Libraries
  33. * @category Security
  34. * @author EllisLab Dev Team
  35. * @link http://codeigniter.com/user_guide/libraries/security.html
  36. */
  37. class CI_Security {
  38. /**
  39. * List of sanitize filename strings
  40. *
  41. * @var array
  42. */
  43. public $filename_bad_chars = array(
  44. '../', '<!--', '-->', '<', '>',
  45. "'", '"', '&', '$', '#',
  46. '{', '}', '[', ']', '=',
  47. ';', '?', '%20', '%22',
  48. '%3c', // <
  49. '%253c', // <
  50. '%3e', // >
  51. '%0e', // >
  52. '%28', // (
  53. '%29', // )
  54. '%2528', // (
  55. '%26', // &
  56. '%24', // $
  57. '%3f', // ?
  58. '%3b', // ;
  59. '%3d' // =
  60. );
  61. /**
  62. * XSS Hash
  63. *
  64. * Random Hash for protecting URLs.
  65. *
  66. * @var string
  67. */
  68. protected $_xss_hash = '';
  69. /**
  70. * CSRF Hash
  71. *
  72. * Random hash for Cross Site Request Forgery protection cookie
  73. *
  74. * @var string
  75. */
  76. protected $_csrf_hash = '';
  77. /**
  78. * CSRF Expire time
  79. *
  80. * Expiration time for Cross Site Request Forgery protection cookie.
  81. * Defaults to two hours (in seconds).
  82. *
  83. * @var int
  84. */
  85. protected $_csrf_expire = 7200;
  86. /**
  87. * CSRF Token name
  88. *
  89. * Token name for Cross Site Request Forgery protection cookie.
  90. *
  91. * @var string
  92. */
  93. protected $_csrf_token_name = 'ci_csrf_token';
  94. /**
  95. * CSRF Cookie name
  96. *
  97. * Cookie name for Cross Site Request Forgery protection cookie.
  98. *
  99. * @var string
  100. */
  101. protected $_csrf_cookie_name = 'ci_csrf_token';
  102. /**
  103. * List of never allowed strings
  104. *
  105. * @var array
  106. */
  107. protected $_never_allowed_str = array(
  108. 'document.cookie' => '[removed]',
  109. 'document.write' => '[removed]',
  110. '.parentNode' => '[removed]',
  111. '.innerHTML' => '[removed]',
  112. 'window.location' => '[removed]',
  113. '-moz-binding' => '[removed]',
  114. '<!--' => '&lt;!--',
  115. '-->' => '--&gt;',
  116. '<![CDATA[' => '&lt;![CDATA[',
  117. '<comment>' => '&lt;comment&gt;'
  118. );
  119. /**
  120. * List of never allowed regex replacements
  121. *
  122. * @var array
  123. */
  124. protected $_never_allowed_regex = array(
  125. 'javascript\s*:',
  126. 'expression\s*(\(|&\#40;)', // CSS and IE
  127. 'vbscript\s*:', // IE, surprise!
  128. 'Redirect\s+302',
  129. "([\"'])?data\s*:[^\\1]*?base64[^\\1]*?,[^\\1]*?\\1?"
  130. );
  131. /**
  132. * Class constructor
  133. *
  134. * @return void
  135. */
  136. public function __construct()
  137. {
  138. // Is CSRF protection enabled?
  139. if (config_item('csrf_protection') === TRUE)
  140. {
  141. // CSRF config
  142. foreach (array('csrf_expire', 'csrf_token_name', 'csrf_cookie_name') as $key)
  143. {
  144. if (FALSE !== ($val = config_item($key)))
  145. {
  146. $this->{'_'.$key} = $val;
  147. }
  148. }
  149. // Append application specific cookie prefix
  150. if (config_item('cookie_prefix'))
  151. {
  152. $this->_csrf_cookie_name = config_item('cookie_prefix').$this->_csrf_cookie_name;
  153. }
  154. // Set the CSRF hash
  155. $this->_csrf_set_hash();
  156. }
  157. log_message('debug', 'Security Class Initialized');
  158. }
  159. // --------------------------------------------------------------------
  160. /**
  161. * CSRF Verify
  162. *
  163. * @return CI_Security
  164. */
  165. public function csrf_verify()
  166. {
  167. // If it's not a POST request we will set the CSRF cookie
  168. if (strtoupper($_SERVER['REQUEST_METHOD']) !== 'POST')
  169. {
  170. return $this->csrf_set_cookie();
  171. }
  172. // Check if URI has been whitelisted from CSRF checks
  173. if ($exclude_uris = config_item('csrf_exclude_uris'))
  174. {
  175. $uri = load_class('URI', 'core');
  176. if (in_array($uri->uri_string(), $exclude_uris))
  177. {
  178. return $this;
  179. }
  180. }
  181. // Do the tokens exist in both the _POST and _COOKIE arrays?
  182. if ( ! isset($_POST[$this->_csrf_token_name], $_COOKIE[$this->_csrf_cookie_name])
  183. OR $_POST[$this->_csrf_token_name] !== $_COOKIE[$this->_csrf_cookie_name]) // Do the tokens match?
  184. {
  185. $this->csrf_show_error();
  186. }
  187. // We kill this since we're done and we don't want to polute the _POST array
  188. unset($_POST[$this->_csrf_token_name]);
  189. // Regenerate on every submission?
  190. if (config_item('csrf_regenerate'))
  191. {
  192. // Nothing should last forever
  193. unset($_COOKIE[$this->_csrf_cookie_name]);
  194. $this->_csrf_hash = '';
  195. }
  196. $this->_csrf_set_hash();
  197. $this->csrf_set_cookie();
  198. log_message('debug', 'CSRF token verified');
  199. return $this;
  200. }
  201. // --------------------------------------------------------------------
  202. /**
  203. * CSRF Set Cookie
  204. *
  205. * @codeCoverageIgnore
  206. * @return CI_Security
  207. */
  208. public function csrf_set_cookie()
  209. {
  210. $expire = time() + $this->_csrf_expire;
  211. $secure_cookie = (bool) config_item('cookie_secure');
  212. if ($secure_cookie && ! is_https())
  213. {
  214. return FALSE;
  215. }
  216. setcookie(
  217. $this->_csrf_cookie_name,
  218. $this->_csrf_hash,
  219. $expire,
  220. config_item('cookie_path'),
  221. config_item('cookie_domain'),
  222. $secure_cookie,
  223. config_item('cookie_httponly')
  224. );
  225. log_message('debug', 'CRSF cookie Set');
  226. return $this;
  227. }
  228. // --------------------------------------------------------------------
  229. /**
  230. * Show CSRF Error
  231. *
  232. * @return void
  233. */
  234. public function csrf_show_error()
  235. {
  236. show_error('The action you have requested is not allowed.');
  237. }
  238. // --------------------------------------------------------------------
  239. /**
  240. * Get CSRF Hash
  241. *
  242. * @see CI_Security::$_csrf_hash
  243. * @return string CSRF hash
  244. */
  245. public function get_csrf_hash()
  246. {
  247. return $this->_csrf_hash;
  248. }
  249. // --------------------------------------------------------------------
  250. /**
  251. * Get CSRF Token Name
  252. *
  253. * @see CI_Security::$_csrf_token_name
  254. * @return string CSRF token name
  255. */
  256. public function get_csrf_token_name()
  257. {
  258. return $this->_csrf_token_name;
  259. }
  260. // --------------------------------------------------------------------
  261. /**
  262. * XSS Clean
  263. *
  264. * Sanitizes data so that Cross Site Scripting Hacks can be
  265. * prevented. This method does a fair amount of work but
  266. * it is extremely thorough, designed to prevent even the
  267. * most obscure XSS attempts. Nothing is ever 100% foolproof,
  268. * of course, but I haven't been able to get anything passed
  269. * the filter.
  270. *
  271. * Note: Should only be used to deal with data upon submission.
  272. * It's not something that should be used for general
  273. * runtime processing.
  274. *
  275. * @link http://channel.bitflux.ch/wiki/XSS_Prevention
  276. * Based in part on some code and ideas from Bitflux.
  277. *
  278. * @link http://ha.ckers.org/xss.html
  279. * To help develop this script I used this great list of
  280. * vulnerabilities along with a few other hacks I've
  281. * harvested from examining vulnerabilities in other programs.
  282. *
  283. * @param string|string[] $str Input data
  284. * @param bool $is_image Whether the input is an image
  285. * @return string
  286. */
  287. public function xss_clean($str, $is_image = FALSE)
  288. {
  289. // Is the string an array?
  290. if (is_array($str))
  291. {
  292. while (list($key) = each($str))
  293. {
  294. $str[$key] = $this->xss_clean($str[$key]);
  295. }
  296. return $str;
  297. }
  298. // Remove Invisible Characters and validate entities in URLs
  299. $str = $this->_validate_entities(remove_invisible_characters($str));
  300. /*
  301. * URL Decode
  302. *
  303. * Just in case stuff like this is submitted:
  304. *
  305. * <a href="http://%77%77%77%2E%67%6F%6F%67%6C%65%2E%63%6F%6D">Google</a>
  306. *
  307. * Note: Use rawurldecode() so it does not remove plus signs
  308. */
  309. $str = rawurldecode($str);
  310. /*
  311. * Convert character entities to ASCII
  312. *
  313. * This permits our tests below to work reliably.
  314. * We only convert entities that are within tags since
  315. * these are the ones that will pose security problems.
  316. */
  317. $str = preg_replace_callback("/[a-z]+=([\'\"]).*?\\1/si", array($this, '_convert_attribute'), $str);
  318. $str = preg_replace_callback('/<\w+.*/si', array($this, '_decode_entity'), $str);
  319. // Remove Invisible Characters Again!
  320. $str = remove_invisible_characters($str);
  321. /*
  322. * Convert all tabs to spaces
  323. *
  324. * This prevents strings like this: ja vascript
  325. * NOTE: we deal with spaces between characters later.
  326. * NOTE: preg_replace was found to be amazingly slow here on
  327. * large blocks of data, so we use str_replace.
  328. */
  329. $str = str_replace("\t", ' ', $str);
  330. // Capture converted string for later comparison
  331. $converted_string = $str;
  332. // Remove Strings that are never allowed
  333. $str = $this->_do_never_allowed($str);
  334. /*
  335. * Makes PHP tags safe
  336. *
  337. * Note: XML tags are inadvertently replaced too:
  338. *
  339. * <?xml
  340. *
  341. * But it doesn't seem to pose a problem.
  342. */
  343. if ($is_image === TRUE)
  344. {
  345. // Images have a tendency to have the PHP short opening and
  346. // closing tags every so often so we skip those and only
  347. // do the long opening tags.
  348. $str = preg_replace('/<\?(php)/i', '&lt;?\\1', $str);
  349. }
  350. else
  351. {
  352. $str = str_replace(array('<?', '?'.'>'), array('&lt;?', '?&gt;'), $str);
  353. }
  354. /*
  355. * Compact any exploded words
  356. *
  357. * This corrects words like: j a v a s c r i p t
  358. * These words are compacted back to their correct state.
  359. */
  360. $words = array(
  361. 'javascript', 'expression', 'vbscript', 'script', 'base64',
  362. 'applet', 'alert', 'document', 'write', 'cookie', 'window'
  363. );
  364. foreach ($words as $word)
  365. {
  366. $word = implode('\s*', str_split($word)).'\s*';
  367. // We only want to do this when it is followed by a non-word character
  368. // That way valid stuff like "dealer to" does not become "dealerto"
  369. $str = preg_replace_callback('#('.substr($word, 0, -3).')(\W)#is', array($this, '_compact_exploded_words'), $str);
  370. }
  371. /*
  372. * Remove disallowed Javascript in links or img tags
  373. * We used to do some version comparisons and use of stripos for PHP5,
  374. * but it is dog slow compared to these simplified non-capturing
  375. * preg_match(), especially if the pattern exists in the string
  376. */
  377. do
  378. {
  379. $original = $str;
  380. if (preg_match('/<a/i', $str))
  381. {
  382. $str = preg_replace_callback('#<a\s+([^>]*?)(?:>|$)#si', array($this, '_js_link_removal'), $str);
  383. }
  384. if (preg_match('/<img/i', $str))
  385. {
  386. $str = preg_replace_callback('#<img\s+([^>]*?)(?:\s?/?>|$)#si', array($this, '_js_img_removal'), $str);
  387. }
  388. if (preg_match('/script|xss/i', $str))
  389. {
  390. $str = preg_replace('#</*(?:script|xss).*?>#si', '[removed]', $str);
  391. }
  392. }
  393. while ($original !== $str);
  394. unset($original);
  395. // Remove evil attributes such as style, onclick and xmlns
  396. $str = $this->_remove_evil_attributes($str, $is_image);
  397. /*
  398. * Sanitize naughty HTML elements
  399. *
  400. * If a tag containing any of the words in the list
  401. * below is found, the tag gets converted to entities.
  402. *
  403. * So this: <blink>
  404. * Becomes: &lt;blink&gt;
  405. */
  406. $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';
  407. $str = preg_replace_callback('#<(/*\s*)('.$naughty.')([^><]*)([><]*)#is', array($this, '_sanitize_naughty_html'), $str);
  408. /*
  409. * Sanitize naughty scripting elements
  410. *
  411. * Similar to above, only instead of looking for
  412. * tags it looks for PHP and JavaScript commands
  413. * that are disallowed. Rather than removing the
  414. * code, it simply converts the parenthesis to entities
  415. * rendering the code un-executable.
  416. *
  417. * For example: eval('some code')
  418. * Becomes: eval&#40;'some code'&#41;
  419. */
  420. $str = preg_replace('#(alert|cmd|passthru|eval|exec|expression|system|fopen|fsockopen|file|file_get_contents|readfile|unlink)(\s*)\((.*?)\)#si',
  421. '\\1\\2&#40;\\3&#41;',
  422. $str);
  423. // Final clean up
  424. // This adds a bit of extra precaution in case
  425. // something got through the above filters
  426. $str = $this->_do_never_allowed($str);
  427. /*
  428. * Images are Handled in a Special Way
  429. * - Essentially, we want to know that after all of the character
  430. * conversion is done whether any unwanted, likely XSS, code was found.
  431. * If not, we return TRUE, as the image is clean.
  432. * However, if the string post-conversion does not matched the
  433. * string post-removal of XSS, then it fails, as there was unwanted XSS
  434. * code found and removed/changed during processing.
  435. */
  436. if ($is_image === TRUE)
  437. {
  438. return ($str === $converted_string);
  439. }
  440. log_message('debug', 'XSS Filtering completed');
  441. return $str;
  442. }
  443. // --------------------------------------------------------------------
  444. /**
  445. * XSS Hash
  446. *
  447. * Generates the XSS hash if needed and returns it.
  448. *
  449. * @see CI_Security::$_xss_hash
  450. * @return string XSS hash
  451. */
  452. public function xss_hash()
  453. {
  454. if ($this->_xss_hash === '')
  455. {
  456. $this->_xss_hash = md5(uniqid(mt_rand()));
  457. }
  458. return $this->_xss_hash;
  459. }
  460. // --------------------------------------------------------------------
  461. /**
  462. * HTML Entities Decode
  463. *
  464. * A replacement for html_entity_decode()
  465. *
  466. * The reason we are not using html_entity_decode() by itself is because
  467. * while it is not technically correct to leave out the semicolon
  468. * at the end of an entity most browsers will still interpret the entity
  469. * correctly. html_entity_decode() does not convert entities without
  470. * semicolons, so we are left with our own little solution here. Bummer.
  471. *
  472. * @link http://php.net/html-entity-decode
  473. *
  474. * @param string $str Input
  475. * @param string $charset Character set
  476. * @return string
  477. */
  478. public function entity_decode($str, $charset = NULL)
  479. {
  480. if (strpos($str, '&') === FALSE)
  481. {
  482. return $str;
  483. }
  484. if (empty($charset))
  485. {
  486. $charset = config_item('charset');
  487. }
  488. do
  489. {
  490. $matches = $matches1 = 0;
  491. $str = preg_replace('~(&#x0*[0-9a-f]{2,5});?~iS', '$1;', $str, -1, $matches);
  492. $str = preg_replace('~(&#\d{2,4});?~S', '$1;', $str, -1, $matches1);
  493. $str = html_entity_decode($str, ENT_COMPAT, $charset);
  494. }
  495. while ($matches OR $matches1);
  496. return $str;
  497. }
  498. // --------------------------------------------------------------------
  499. /**
  500. * Sanitize Filename
  501. *
  502. * @param string $str Input file name
  503. * @param bool $relative_path Whether to preserve paths
  504. * @return string
  505. */
  506. public function sanitize_filename($str, $relative_path = FALSE)
  507. {
  508. $bad = $this->filename_bad_chars;
  509. if ( ! $relative_path)
  510. {
  511. $bad[] = './';
  512. $bad[] = '/';
  513. }
  514. $str = remove_invisible_characters($str, FALSE);
  515. do
  516. {
  517. $old = $str;
  518. $str = str_replace($bad, '', $str);
  519. }
  520. while ($old !== $str);
  521. return stripslashes($str);
  522. }
  523. // ----------------------------------------------------------------
  524. /**
  525. * Strip Image Tags
  526. *
  527. * @param string $str
  528. * @return string
  529. */
  530. public function strip_image_tags($str)
  531. {
  532. return preg_replace(array('#<img[\s/]+.*?src\s*=\s*["\'](.+?)["\'].*?\>#', '#<img[\s/]+.*?src\s*=\s*(.+?).*?\>#'), '\\1', $str);
  533. }
  534. // ----------------------------------------------------------------
  535. /**
  536. * Compact Exploded Words
  537. *
  538. * Callback method for xss_clean() to remove whitespace from
  539. * things like 'j a v a s c r i p t'.
  540. *
  541. * @used-by CI_Security::xss_clean()
  542. * @param array $matches
  543. * @return string
  544. */
  545. protected function _compact_exploded_words($matches)
  546. {
  547. return preg_replace('/\s+/s', '', $matches[1]).$matches[2];
  548. }
  549. // --------------------------------------------------------------------
  550. /**
  551. * Remove Evil HTML Attributes (like event handlers and style)
  552. *
  553. * It removes the evil attribute and either:
  554. *
  555. * - Everything up until a space. For example, everything between the pipes:
  556. *
  557. * <code>
  558. * <a |style=document.write('hello');alert('world');| class=link>
  559. * </code>
  560. *
  561. * - Everything inside the quotes. For example, everything between the pipes:
  562. *
  563. * <code>
  564. * <a |style="document.write('hello'); alert('world');"| class="link">
  565. * </code>
  566. *
  567. * @param string $str The string to check
  568. * @param bool $is_image Whether the input is an image
  569. * @return string The string with the evil attributes removed
  570. */
  571. protected function _remove_evil_attributes($str, $is_image)
  572. {
  573. // All javascript event handlers (e.g. onload, onclick, onmouseover), style, and xmlns
  574. $evil_attributes = array('on\w*', 'style', 'xmlns', 'formaction');
  575. if ($is_image === TRUE)
  576. {
  577. /*
  578. * Adobe Photoshop puts XML metadata into JFIF images,
  579. * including namespacing, so we have to allow this for images.
  580. */
  581. unset($evil_attributes[array_search('xmlns', $evil_attributes)]);
  582. }
  583. do {
  584. $count = 0;
  585. $attribs = array();
  586. // find occurrences of illegal attribute strings with quotes (042 and 047 are octal quotes)
  587. preg_match_all('/('.implode('|', $evil_attributes).')\s*=\s*(\042|\047)([^\\2]*?)(\\2)/is', $str, $matches, PREG_SET_ORDER);
  588. foreach ($matches as $attr)
  589. {
  590. $attribs[] = preg_quote($attr[0], '/');
  591. }
  592. // find occurrences of illegal attribute strings without quotes
  593. preg_match_all('/('.implode('|', $evil_attributes).')\s*=\s*([^\s>]*)/is', $str, $matches, PREG_SET_ORDER);
  594. foreach ($matches as $attr)
  595. {
  596. $attribs[] = preg_quote($attr[0], '/');
  597. }
  598. // replace illegal attribute strings that are inside an html tag
  599. if (count($attribs) > 0)
  600. {
  601. $str = preg_replace('/(<?)(\/?[^><]+?)([^A-Za-z<>\-])(.*?)('.implode('|', $attribs).')(.*?)([\s><]?)([><]*)/i', '$1$2 $4$6$7$8', $str, -1, $count);
  602. }
  603. }
  604. while ($count);
  605. return $str;
  606. }
  607. // --------------------------------------------------------------------
  608. /**
  609. * Sanitize Naughty HTML
  610. *
  611. * Callback method for xss_clean() to remove naughty HTML elements.
  612. *
  613. * @used-by CI_Security::xss_clean()
  614. * @param array $matches
  615. * @return string
  616. */
  617. protected function _sanitize_naughty_html($matches)
  618. {
  619. return '&lt;'.$matches[1].$matches[2].$matches[3] // encode opening brace
  620. // encode captured opening or closing brace to prevent recursive vectors:
  621. .str_replace(array('>', '<'), array('&gt;', '&lt;'), $matches[4]);
  622. }
  623. // --------------------------------------------------------------------
  624. /**
  625. * JS Link Removal
  626. *
  627. * Callback method for xss_clean() to sanitize links.
  628. *
  629. * This limits the PCRE backtracks, making it more performance friendly
  630. * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in
  631. * PHP 5.2+ on link-heavy strings.
  632. *
  633. * @used-by CI_Security::xss_clean()
  634. * @param array $match
  635. * @return string
  636. */
  637. protected function _js_link_removal($match)
  638. {
  639. return str_replace($match[1],
  640. preg_replace('#href=.*?(?:alert\(|alert&\#40;|javascript:|livescript:|mocha:|charset=|window\.|document\.|\.cookie|<script|<xss|data\s*:)#si',
  641. '',
  642. $this->_filter_attributes(str_replace(array('<', '>'), '', $match[1]))
  643. ),
  644. $match[0]);
  645. }
  646. // --------------------------------------------------------------------
  647. /**
  648. * JS Image Removal
  649. *
  650. * Callback method for xss_clean() to sanitize image tags.
  651. *
  652. * This limits the PCRE backtracks, making it more performance friendly
  653. * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in
  654. * PHP 5.2+ on image tag heavy strings.
  655. *
  656. * @used-by CI_Security::xss_clean()
  657. * @param array $match
  658. * @return string
  659. */
  660. protected function _js_img_removal($match)
  661. {
  662. return str_replace($match[1],
  663. preg_replace('#src=.*?(?:alert\(|alert&\#40;|javascript:|livescript:|mocha:|charset=|window\.|document\.|\.cookie|<script|<xss|base64\s*,)#si',
  664. '',
  665. $this->_filter_attributes(str_replace(array('<', '>'), '', $match[1]))
  666. ),
  667. $match[0]);
  668. }
  669. // --------------------------------------------------------------------
  670. /**
  671. * Attribute Conversion
  672. *
  673. * @used-by CI_Security::xss_clean()
  674. * @param array $match
  675. * @return string
  676. */
  677. protected function _convert_attribute($match)
  678. {
  679. return str_replace(array('>', '<', '\\'), array('&gt;', '&lt;', '\\\\'), $match[0]);
  680. }
  681. // --------------------------------------------------------------------
  682. /**
  683. * Filter Attributes
  684. *
  685. * Filters tag attributes for consistency and safety.
  686. *
  687. * @used-by CI_Security::_js_img_removal()
  688. * @used-by CI_Security::_js_link_removal()
  689. * @param string $str
  690. * @return string
  691. */
  692. protected function _filter_attributes($str)
  693. {
  694. $out = '';
  695. if (preg_match_all('#\s*[a-z\-]+\s*=\s*(\042|\047)([^\\1]*?)\\1#is', $str, $matches))
  696. {
  697. foreach ($matches[0] as $match)
  698. {
  699. $out .= preg_replace('#/\*.*?\*/#s', '', $match);
  700. }
  701. }
  702. return $out;
  703. }
  704. // --------------------------------------------------------------------
  705. /**
  706. * HTML Entity Decode Callback
  707. *
  708. * @used-by CI_Security::xss_clean()
  709. * @param array $match
  710. * @return string
  711. */
  712. protected function _decode_entity($match)
  713. {
  714. return $this->entity_decode($match[0], strtoupper(config_item('charset')));
  715. }
  716. // --------------------------------------------------------------------
  717. /**
  718. * Validate URL entities
  719. *
  720. * @used-by CI_Security::xss_clean()
  721. * @param string $str
  722. * @return string
  723. */
  724. protected function _validate_entities($str)
  725. {
  726. /*
  727. * Protect GET variables in URLs
  728. */
  729. // 901119URL5918AMP18930PROTECT8198
  730. $str = preg_replace('|\&([a-z\_0-9\-]+)\=([a-z\_0-9\-]+)|i', $this->xss_hash().'\\1=\\2', $str);
  731. /*
  732. * Validate standard character entities
  733. *
  734. * Add a semicolon if missing. We do this to enable
  735. * the conversion of entities to ASCII later.
  736. */
  737. $str = preg_replace('#(&\#?[0-9a-z]{2,})([\x00-\x20])*;?#i', '\\1;\\2', $str);
  738. /*
  739. * Validate UTF16 two byte encoding (x00)
  740. *
  741. * Just as above, adds a semicolon if missing.
  742. */
  743. $str = preg_replace('#(&\#x?)([0-9A-F]+);?#i', '\\1\\2;', $str);
  744. /*
  745. * Un-Protect GET variables in URLs
  746. */
  747. return str_replace($this->xss_hash(), '&', $str);
  748. }
  749. // ----------------------------------------------------------------------
  750. /**
  751. * Do Never Allowed
  752. *
  753. * @used-by CI_Security::xss_clean()
  754. * @param string
  755. * @return string
  756. */
  757. protected function _do_never_allowed($str)
  758. {
  759. $str = str_replace(array_keys($this->_never_allowed_str), $this->_never_allowed_str, $str);
  760. foreach ($this->_never_allowed_regex as $regex)
  761. {
  762. $str = preg_replace('#'.$regex.'#is', '[removed]', $str);
  763. }
  764. return $str;
  765. }
  766. // --------------------------------------------------------------------
  767. /**
  768. * Set CSRF Hash and Cookie
  769. *
  770. * @return string
  771. */
  772. protected function _csrf_set_hash()
  773. {
  774. if ($this->_csrf_hash === '')
  775. {
  776. // If the cookie exists we will use its value.
  777. // We don't necessarily want to regenerate it with
  778. // each page load since a page could contain embedded
  779. // sub-pages causing this feature to fail
  780. if (isset($_COOKIE[$this->_csrf_cookie_name]) &&
  781. preg_match('#^[0-9a-f]{32}$#iS', $_COOKIE[$this->_csrf_cookie_name]) === 1)
  782. {
  783. return $this->_csrf_hash = $_COOKIE[$this->_csrf_cookie_name];
  784. }
  785. $this->_csrf_hash = md5(uniqid(mt_rand(), TRUE));
  786. $this->csrf_set_cookie();
  787. }
  788. return $this->_csrf_hash;
  789. }
  790. }
  791. /* End of file Security.php */
  792. /* Location: ./system/core/Security.php */