CI安全類提供了全域防禦CSRF攻擊和XSS攻擊策略,只需要在設定檔開啟即可:
複製代碼 代碼如下:
$config['csrf_protection'] = TRUE;
$config['global_xss_filtering'] = TRUE;
並提供了實用方法:
複製代碼 代碼如下:
$this->security->xss_clean($data);//第二個參數為TRUE,驗證圖片安全
$this->security->sanitize_filename()//過濾檔案名稱
CI也提供了安全函數:
xss_clean()//xss過濾
sanitize_filename()//淨化檔案名稱
do_hash()//md5或sha加密
strip_image_tags() //刪除圖片標籤的不必要字元
encode_php_tags()//把PHP指令碼標籤強制轉成實體物件
複製代碼 代碼如下:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* 安全類
*/
class CI_Security {
//url的隨機hash值
protected $_xss_hash = '';
//防csrf攻擊的cookie標記的雜湊值
protected $_csrf_hash = '';
//防csrf cookie到期時間
protected $_csrf_expire = 7200;
//防csrf的cookie名稱
protected $_csrf_token_name = 'ci_csrf_token';
//防csrf的token名稱
protected $_csrf_cookie_name = 'ci_csrf_token';
//不允許出現的字串數組
protected $_never_allowed_str = array(
'document.cookie' => '[removed]',
'document.write' => '[removed]',
'.parentNode' => '[removed]',
'.innerHTML' => '[removed]',
'window.location' => '[removed]',
'-moz-binding' => '[removed]',
'' => '-->',
'' => '<![CDATA[',<br /> '<comment>' => '<comment>'<br /> );<br /> //不允許出現的Regex數組<br /> protected $_never_allowed_regex = array(<br /> 'javascript\s*:',<br /> 'expression\s*(\(|&\#40;)', // CSS and IE<br /> 'vbscript\s*:', // IE, surprise!<br /> 'Redirect\s+302',<br /> "([\"'])?data\s*:[^\\1]*?base64[^\\1]*?,[^\\1]*?\\1?"<br /> );<br /> //建構函式<br /> public function __construct()<br /> {<br /> // CSRF保護是否開啟<br /> if (config_item('csrf_protection') === TRUE)<br /> {<br /> // CSRF配置<br /> foreach (array('csrf_expire', 'csrf_token_name', 'csrf_cookie_name') as $key)<br /> {<br /> if (FALSE !== ($val = config_item($key)))<br /> {<br /> $this->{'_'.$key} = $val;<br /> }<br /> }<br /> // _csrf_cookie_name加上cookie首碼<br /> if (config_item('cookie_prefix'))<br /> {<br /> $this->_csrf_cookie_name = config_item('cookie_prefix').$this->_csrf_cookie_name;<br /> }<br /> // 設定csrf的hash值<br /> $this->_csrf_set_hash();<br /> }<br /> log_message('debug', "Security Class Initialized");<br /> }<br /> // --------------------------------------------------------------------<br /> /**<br /> * Verify Cross Site Request Forgery Protection<br /> *<br /> * @return object<br /> */<br /> public function csrf_verify()<br /> {<br /> // 如果不是post請求,則設定csrf的cookie值<br /> if (strtoupper($_SERVER['REQUEST_METHOD']) !== 'POST')<br /> {<br /> return $this->csrf_set_cookie();<br /> }<br /> // Do the tokens exist in both the _POST and _COOKIE arrays?<br /> if ( ! isset($_POST[$this->_csrf_token_name], $_COOKIE[$this->_csrf_cookie_name]))<br /> {<br /> $this->csrf_show_error();<br /> }<br /> // token匹配嗎<br /> if ($_POST[$this->_csrf_token_name] != $_COOKIE[$this->_csrf_cookie_name])<br /> {<br /> $this->csrf_show_error();<br /> }<br /> // We kill this since we're done and we don't want to<br /> // polute the _POST array<br /> unset($_POST[$this->_csrf_token_name]);<br /> // Nothing should last forever<br /> unset($_COOKIE[$this->_csrf_cookie_name]);<br /> $this->_csrf_set_hash();<br /> $this->csrf_set_cookie();<br /> log_message('debug', 'CSRF token verified');<br /> return $this;<br /> }<br /> // --------------------------------------------------------------------<br /> /**<br /> * 設定csrf的cookie值<br /> */<br /> public function csrf_set_cookie()<br /> {<br /> $expire = time() + $this->_csrf_expire;<br /> $secure_cookie = (config_item('cookie_secure') === TRUE) ? 1 : 0;<br /> if ($secure_cookie && (empty($_SERVER['HTTPS']) OR strtolower($_SERVER['HTTPS']) === 'off'))<br /> {<br /> return FALSE;<br /> }<br /> setcookie($this->_csrf_cookie_name, $this->_csrf_hash, $expire, config_item('cookie_path'), config_item('cookie_domain'), $secure_cookie);<br /> log_message('debug', "CRSF cookie Set");<br /> return $this;<br /> }<br /> //csrf儲存<br /> public function csrf_show_error()<br /> {<br /> show_error('The action you have requested is not allowed.');<br /> }<br /> //擷取csrf的hash值<br /> public function get_csrf_hash()<br /> {<br /> return $this->_csrf_hash;<br /> }<br /> //擷取csrf的token值<br /> public function get_csrf_token_name()<br /> {<br /> return $this->_csrf_token_name;<br /> }<br /> /**<br /> * XSS 過濾<br /> */<br /> public function xss_clean($str, $is_image = FALSE)<br /> {<br /> //是否是數組<br /> if (is_array($str))<br /> {<br /> while (list($key) = each($str))<br /> {<br /> $str[$key] = $this->xss_clean($str[$key]);<br /> }<br /> return $str;<br /> }<br /> //去掉可見字串<br /> $str = remove_invisible_characters($str);<br /> // 驗證實體url<br /> $str = $this->_validate_entities($str);<br /> /*<br /> * URL 解碼<br /> *<br /> * Just in case stuff like this is submitted:<br /> *<br /> * Google<br /> *<br /> * Note: Use rawurldecode() so it does not remove plus signs<br /> *<br /> */<br /> $str = rawurldecode($str);<br /> /*<br /> * Convert character entities to ASCII<br /> *<br /> * This permits our tests below to work reliably.<br /> * We only convert entities that are within tags since<br /> * these are the ones that will pose security problems.<br /> *<br /> */<br /> $str = preg_replace_callback("/[a-z]+=([\'\"]).*?\\1/si", array($this, '_convert_attribute'), $str);<br /> $str = preg_replace_callback("/<\w+.*?(?=>|<|$)/si", array($this, '_decode_entity'), $str);<br /> /*<br /> * Remove Invisible Characters Again!<br /> */<br /> $str = remove_invisible_characters($str);<br /> /*<br /> * Convert all tabs to spaces<br /> *<br /> * This prevents strings like this: ja vascript<br /> * NOTE: we deal with spaces between characters later.<br /> * NOTE: preg_replace was found to be amazingly slow here on<br /> * large blocks of data, so we use str_replace.<br /> */<br /> if (strpos($str, "\t") !== FALSE)<br /> {<br /> $str = str_replace("\t", ' ', $str);<br /> }<br /> /*<br /> * Capture converted string for later comparison<br /> */<br /> $converted_string = $str;<br /> // Remove Strings that are never allowed<br /> $str = $this->_do_never_allowed($str);<br /> /*<br /> * Makes PHP tags safe<br /> *<br /> * Note: XML tags are inadvertently replaced too:<br /> *<br /> * <?xml<br /> *<br /> * But it doesn't seem to pose a problem.<br /> */<br /> if ($is_image === TRUE)<br /> {<br /> // Images have a tendency to have the PHP short opening and<br /> // closing tags every so often so we skip those and only<br /> // do the long opening tags.<br /> $str = preg_replace('/<\?(php)/i', "<?\\1", $str);<br /> }<br /> else<br /> {<br /> $str = str_replace(array('<?', '?'.'>'), array('<?', '?>'), $str);<br /> }<br /> /*<br /> * Compact any exploded words<br /> *<br /> * This corrects words like: j a v a s c r i p t<br /> * These words are compacted back to their correct state.<br /> */<br /> $words = array(<br /> 'javascript', 'expression', 'vbscript', 'script', 'base64',<br /> 'applet', 'alert', 'document', 'write', 'cookie', 'window'<br /> );<br /> foreach ($words as $word)<br /> {<br /> $temp = '';<br /> for ($i = 0, $wordlen = strlen($word); $i < $wordlen; $i++)<br /> {<br /> $temp .= substr($word, $i, 1)."\s*";<br /> }<br /> // We only want to do this when it is followed by a non-word character<br /> // That way valid stuff like "dealer to" does not become "dealerto"<br /> $str = preg_replace_callback('#('.substr($temp, 0, -3).')(\W)#is', array($this, '_compact_exploded_words'), $str);<br /> }<br /> /*<br /> * Remove disallowed Javascript in links or img tags<br /> * We used to do some version comparisons and use of stripos for PHP5,<br /> * but it is dog slow compared to these simplified non-capturing<br /> * preg_match(), especially if the pattern exists in the string<br /> */<br /> do<br /> {<br /> $original = $str;<br /> if (preg_match("/ {<br /> $str = preg_replace_callback("#]*?)(>|$)#si", array($this, '_js_link_removal'), $str);<br /> }<br /> if (preg_match("/ {<br /> $str = preg_replace_callback("#]*?)(\s?/?>|$)#si", array($this, '_js_img_removal'), $str);<br /> }<br /> if (preg_match("/script/i", $str) OR preg_match("/xss/i", $str))<br /> {<br /> $str = preg_replace("#<(/*)(script|xss)(.*?)\>#si", '[removed]', $str);<br /> }<br /> }<br /> while($original != $str);<br /> unset($original);<br /> // Remove evil attributes such as style, onclick and xmlns<br /> $str = $this->_remove_evil_attributes($str, $is_image);<br /> /*<br /> * Sanitize naughty HTML elements<br /> *<br /> * If a tag containing any of the words in the list<br /> * below is found, the tag gets converted to entities.<br /> *<br /> * So this: <blink><br /> * Becomes: <blink><br /> */<br /> $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';<br /> $str = preg_replace_callback('#<(/*\s*)('.$naughty.')([^><]*)([><]*)#is', array($this, '_sanitize_naughty_html'), $str);<br /> /*<br /> * Sanitize naughty scripting elements<br /> *<br /> * Similar to above, only instead of looking for<br /> * tags it looks for PHP and JavaScript commands<br /> * that are disallowed. Rather than removing the<br /> * code, it simply converts the parenthesis to entities<br /> * rendering the code un-executable.<br /> *<br /> * For example: eval('some code')<br /> * Becomes: eval('some code')<br /> */<br /> $str = preg_replace('#(alert|cmd|passthru|eval|exec|expression|system|fopen|fsockopen|file|file_get_contents|readfile|unlink)(\s*)\((.*?)\)#si', "\\1\\2(\\3)", $str);<br /> // Final clean up<br /> // This adds a bit of extra precaution in case<br /> // something got through the above filters<br /> $str = $this->_do_never_allowed($str);<br /> /*<br /> * Images are Handled in a Special Way<br /> * - Essentially, we want to know that after all of the character<br /> * conversion is done whether any unwanted, likely XSS, code was found.<br /> * If not, we return TRUE, as the image is clean.<br /> * However, if the string post-conversion does not matched the<br /> * string post-removal of XSS, then it fails, as there was unwanted XSS<br /> * code found and removed/changed during processing.<br /> */<br /> if ($is_image === TRUE)<br /> {<br /> return ($str == $converted_string) ? TRUE: FALSE;<br /> }<br /> log_message('debug', "XSS Filtering completed");<br /> return $str;<br /> }<br /> // --------------------------------------------------------------------<br /> //保護url的隨機hash值<br /> public function xss_hash()<br /> {<br /> if ($this->_xss_hash == '')<br /> {<br /> mt_srand();<br /> $this->_xss_hash = md5(time() + mt_rand(0, 1999999999));<br /> }<br /> return $this->_xss_hash;<br /> }<br /> // --------------------------------------------------------------------<br /> /**<br /> * html實體轉碼<br /> */<br /> public function entity_decode($str, $charset='UTF-8')<br /> {<br /> if (stristr($str, '&') === FALSE)<br /> {<br /> return $str;<br /> }<br /> $str = html_entity_decode($str, ENT_COMPAT, $charset);<br /> $str = preg_replace('~&#x(0*[0-9a-f]{2,5})~ei', 'chr(hexdec("\\1"))', $str);<br /> return preg_replace('~&#([0-9]{2,4})~e', 'chr(\\1)', $str);<br /> }<br /> // --------------------------------------------------------------------<br /> //過濾檔案名稱,保證檔案名稱安全<br /> public function sanitize_filename($str, $relative_path = FALSE)<br /> {<br /> $bad = array(<br /> "../",<br /> "<!--",<br /> "-->",<br /> "<",<br /> ">",<br /> "'",<br /> '"',<br /> '&',<br /> '$',<br /> '#',<br /> '{',<br /> '}',<br /> '[',<br /> ']',<br /> '=',<br /> ';',<br /> '?',<br /> "%20",<br /> "%22",<br /> "%3c", // <<br /> "%253c", // <<br /> "%3e", // ><br /> "%0e", // ><br /> "%28", // (<br /> "%29", // )<br /> "%2528", // (<br /> "%26", // &<br /> "%24", // $<br /> "%3f", // ?<br /> "%3b", // ;<br /> "%3d" // =<br /> );<br /> if ( ! $relative_path)<br /> {<br /> $bad[] = './';<br /> $bad[] = '/';<br /> }<br /> $str = remove_invisible_characters($str, FALSE);<br /> return stripslashes(str_replace($bad, '', $str));<br /> }<br /> //壓縮單詞如j a v a s c r i p t成javascript<br /> protected function _compact_exploded_words($matches)<br /> {<br /> return preg_replace('/\s+/s', '', $matches[1]).$matches[2];<br /> }<br /> // --------------------------------------------------------------------<br /> /*<br /> * 去掉一些危害的html屬性<br /> */<br /> protected function _remove_evil_attributes($str, $is_image)<br /> {<br /> // All javascript event handlers (e.g. onload, onclick, onmouseover), style, and xmlns<br /> $evil_attributes = array('on\w*', 'style', 'xmlns', 'formaction');<br /> if ($is_image === TRUE)<br /> {<br /> /*<br /> * Adobe Photoshop puts XML metadata into JFIF images, <br /> * including namespacing, so we have to allow this for images.<br /> */<br /> unset($evil_attributes[array_search('xmlns', $evil_attributes)]);<br /> }<br /> do {<br /> $count = 0;<br /> $attribs = array();<br /> // find occurrences of illegal attribute strings with quotes (042 and 047 are octal quotes)<br /> preg_match_all('/('.implode('|', $evil_attributes).')\s*=\s*(\042|\047)([^\\2]*?)(\\2)/is', $str, $matches, PREG_SET_ORDER);<br /> foreach ($matches as $attr)<br /> {<br /> $attribs[] = preg_quote($attr[0], '/');<br /> }<br /> // find occurrences of illegal attribute strings without quotes<br /> preg_match_all('/('.implode('|', $evil_attributes).')\s*=\s*([^\s>]*)/is', $str, $matches, PREG_SET_ORDER);<br /> foreach ($matches as $attr)<br /> {<br /> $attribs[] = preg_quote($attr[0], '/');<br /> }<br /> // replace illegal attribute strings that are inside an html tag<br /> if (count($attribs) > 0)<br /> {<br /> $str = preg_replace('/(<?)(\/?[^><]+?)([^A-Za-z<>\-])(.*?)('.implode('|', $attribs).')(.*?)([\s><]?)([><]*)/i', '$1$2 $4$6$7$8', $str, -1, $count);<br /> }<br /> } while ($count);<br /> return $str;<br /> }<br /> // --------------------------------------------------------------------<br /> /**<br /> * 淨化html,補齊未關閉的標籤<br /> */<br /> protected function _sanitize_naughty_html($matches)<br /> {<br /> // encode opening brace<br /> $str = '<'.$matches[1].$matches[2].$matches[3];<br /> // encode captured opening or closing brace to prevent recursive vectors<br /> $str .= str_replace(array('>', '<'), array('>', '<'),<br /> $matches[4]);<br /> return $str;<br /> }<br /> // --------------------------------------------------------------------<br /> /**<br /> * 過濾超連結中js<br /> */<br /> protected function _js_link_removal($match)<br /> {<br /> return str_replace(<br /> $match[1],<br /> preg_replace(<br /> '#href=.*?(alert\(|alert&\#40;|javascript\:|livescript\:|mocha\:|charset\=|window\.|document\.|\.cookie|<script|<xss|data\s*:)#si',<br /> '',<br /> $this->_filter_attributes(str_replace(array('<', '>'), '', $match[1]))<br /> ),<br /> $match[0]<br /> );<br /> }<br /> // --------------------------------------------------------------------<br /> /**<br /> * 過濾圖片連結中的js<br /> */<br /> protected function _js_img_removal($match)<br /> {<br /> return str_replace(<br /> $match[1],<br /> preg_replace(<br /> '#src=.*?(alert\(|alert&\#40;|javascript\:|livescript\:|mocha\:|charset\=|window\.|document\.|\.cookie|<script|<xss|base64\s*,)#si',<br /> '',<br /> $this->_filter_attributes(str_replace(array('<', '>'), '', $match[1]))<br /> ),<br /> $match[0]<br /> );<br /> }<br /> // --------------------------------------------------------------------<br /> /**<br /> * 轉換屬性,將一些字元轉換成實體<br /> */<br /> protected function _convert_attribute($match)<br /> {<br /> return str_replace(array('>', '<', '\\'), array('>', '<', '\\\\'), $match[0]);<br /> }<br /> // --------------------------------------------------------------------<br /> //過濾html標籤屬性<br /> protected function _filter_attributes($str)<br /> {<br /> $out = '';<br /> if (preg_match_all('#\s*[a-z\-]+\s*=\s*(\042|\047)([^\\1]*?)\\1#is', $str, $matches))<br /> {<br /> foreach ($matches[0] as $match)<br /> {<br /> $out .= preg_replace("#/\*.*?\*/#s", '', $match);<br /> }<br /> }<br /> return $out;<br /> }<br /> // --------------------------------------------------------------------<br /> //html實體轉碼<br /> protected function _decode_entity($match)<br /> {<br /> return $this->entity_decode($match[0], strtoupper(config_item('charset')));<br /> }<br /> // --------------------------------------------------------------------<br /> /**<br /> * 驗證url實體<br /> */<br /> protected function _validate_entities($str)<br /> {<br /> /*<br /> * Protect GET variables in URLs<br /> */<br /> // 901119URL5918AMP18930PROTECT8198<br /> $str = preg_replace('|\&([a-z\_0-9\-]+)\=([a-z\_0-9\-]+)|i', $this->xss_hash()."\\1=\\2", $str);<br /> /*<br /> * Validate standard character entities<br /> *<br /> * Add a semicolon if missing. We do this to enable<br /> * the conversion of entities to ASCII later.<br /> *<br /> */<br /> $str = preg_replace('#(&\#?[0-9a-z]{2,})([\x00-\x20])*;?#i', "\\1;\\2", $str);<br /> /*<br /> * Validate UTF16 two byte encoding (x00)<br /> *<br /> * Just as above, adds a semicolon if missing.<br /> *<br /> */<br /> $str = preg_replace('#(&\#x?)([0-9A-F]+);?#i',"\\1\\2;",$str);<br /> /*<br /> * Un-Protect GET variables in URLs<br /> */<br /> $str = str_replace($this->xss_hash(), '&', $str);<br /> return $str;<br /> }<br /> // ----------------------------------------------------------------------<br /> //過濾不允許出現的字串<br /> protected function _do_never_allowed($str)<br /> {<br /> $str = str_replace(array_keys($this->_never_allowed_str), $this->_never_allowed_str, $str);<br /> foreach ($this->_never_allowed_regex as $regex)<br /> {<br /> $str = preg_replace('#'.$regex.'#is', '[removed]', $str);<br /> }<br /> return $str;<br /> }<br /> // --------------------------------------------------------------------<br /> //設定csrf的hash值<br /> protected function _csrf_set_hash()<br /> {<br /> if ($this->_csrf_hash == '')<br /> {<br /> // 如果_csrf_cookie_name存在,直接作為csrf hash值<br /> if (isset($_COOKIE[$this->_csrf_cookie_name]) &&<br /> preg_match('#^[0-9a-f]{32}$#iS', $_COOKIE[$this->_csrf_cookie_name]) === 1)<br /> {<br /> return $this->_csrf_hash = $_COOKIE[$this->_csrf_cookie_name];<br /> }<br /> //否則隨機一個md5字串<br /> return $this->_csrf_hash = md5(uniqid(rand(), TRUE));<br /> }<br /> return $this->_csrf_hash;<br /> }<br />}<br /><li ><i class="layui-icon">