一、構造函數:
首先判斷CSRF保護是否開啓,若開啓,則初始化CSRF配置,然後添加cookie prefix前綴,最後設置CSRF hash:
public function __construct()
{
// Is CSRF protection enabled?
if (config_item('csrf_protection') === TRUE)
{
// CSRF config
foreach (array('csrf_expire', 'csrf_token_name', 'csrf_cookie_name') as $key)
{
if (FALSE !== ($val = config_item($key)))
{
$this->{'_'.$key} = $val;
}
}
// Append application specific cookie prefix
if (config_item('cookie_prefix'))
{
$this->_csrf_cookie_name = config_item('cookie_prefix').$this->_csrf_cookie_name;
}
// Set the CSRF hash
$this->_csrf_set_hash();
}
log_message('debug', "Security Class Initialized");
}
其中_csrf_set_hash()方法是設置CSRF保護cookie,首先判斷_csrf_cookie_name是否設置(即在config.php中設置),且是否被正則表達式匹配,則$this->_csrf_hash = $_COOKIE[$this->_csrf_cookie_name];否則$this->_csrf_hash = md5(uniqid(rand(), TRUE));
protected function _csrf_set_hash()
{
if ($this->_csrf_hash == '')
{
// If the cookie exists we will use it's value.
// We don't necessarily want to regenerate it with
// each page load since a page could contain embedded
// sub-pages causing this feature to fail
if (isset($_COOKIE[$this->_csrf_cookie_name]) &&
preg_match('#^[0-9a-f]{32}$#iS', $_COOKIE[$this->_csrf_cookie_name]) === 1)
{
return $this->_csrf_hash = $_COOKIE[$this->_csrf_cookie_name];
}
return $this->_csrf_hash = md5(uniqid(rand(), TRUE));
}
return $this->_csrf_hash;
}
二、驗證CSRF保護
首先判斷是不是POST請求,如果不是POST請求則調用$this->csrf_set_cookie()設置CSRF cookie,然後判斷token和cookie是否存在,再判斷POST過來的_csrf_token_name和cookies中的_csrf_cookie_name是否相等,否則顯示錯誤頁面,然後立即unset($_POST[$this->_csrf_token_name]);和unset($_COOKIE[$this->_csrf_cookie_name]);
public function csrf_verify()
{
// If it's not a POST request we will set the CSRF cookie
if (strtoupper($_SERVER['REQUEST_METHOD']) !== 'POST')
{
return $this->csrf_set_cookie();
}
// Do the tokens exist in both the _POST and _COOKIE arrays?
if ( ! isset($_POST[$this->_csrf_token_name], $_COOKIE[$this->_csrf_cookie_name]))
{
$this->csrf_show_error();
}
// Do the tokens match?
if ($_POST[$this->_csrf_token_name] != $_COOKIE[$this->_csrf_cookie_name])
{
$this->csrf_show_error();
}
// We kill this since we're done and we don't want to
// polute the _POST array
unset($_POST[$this->_csrf_token_name]);
// Nothing should last forever
unset($_COOKIE[$this->_csrf_cookie_name]);
$this->_csrf_set_hash();
$this->csrf_set_cookie();
log_message('debug', 'CSRF token verified');
return $this;
}
csrf_set_cookie()代碼如下:
public function csrf_set_cookie()
{
$expire = time() + $this->_csrf_expire;
$secure_cookie = (config_item('cookie_secure') === TRUE) ? 1 : 0;
if ($secure_cookie && (empty($_SERVER['HTTPS']) OR strtolower($_SERVER['HTTPS']) === 'off'))
{
return FALSE;
}
setcookie($this->_csrf_cookie_name, $this->_csrf_hash, $expire, config_item('cookie_path'), config_item('cookie_domain'), $secure_cookie);
log_message('debug', "CRSF cookie Set");
return $this;
}
三、xss_clean():對數據進行過濾,函數原型:public function xss_clean($str, $is_image = FALSE),傳入需要過濾的字符串
該函數分以下幾個步驟過濾字符串:
①判斷字符串是否爲數組,則遞歸調用xss_clean()過濾
if (is_array($str))
{
while (list($key) = each($str))
{
$str[$key] = $this->xss_clean($str[$key]);
}
return $str;
}
②:去除ASCII字符之間插入的空字符,如java\0script
$str = remove_invisible_characters($str);
③:驗證URL實體:調用私有方法$str = $this->_validate_entities($str);
protected function _validate_entities($str)
{
/*
* Protect GET variables in URLs
*/
// 901119URL5918AMP18930PROTECT8198
$str = preg_replace('|\&([a-z\_0-9\-]+)\=([a-z\_0-9\-]+)|i', $this->xss_hash()."\\1=\\2", $str);
/*
* Validate standard character entities
*
* Add a semicolon if missing. We do this to enable
* the conversion of entities to ASCII later.
*
*/
$str = preg_replace('#(&\#?[0-9a-z]{2,})([\x00-\x20])*;?#i', "\\1;\\2", $str);
/*
* Validate UTF16 two byte encoding (x00)
*
* Just as above, adds a semicolon if missing.
*
*/
$str = preg_replace('#(&\#x?)([0-9A-F]+);?#i',"\\1\\2;",$str);
/*
* Un-Protect GET variables in URLs
*/
$str = str_replace($this->xss_hash(), '&', $str);
return $str;
}
④:對已編碼的URL字符串進行解碼:
$str = rawurldecode($str);
⑤:轉換字符實體爲ASCII:使用preg_replace_callback調用回調函數_convert_attribute和_decode_entity
$str = preg_replace_callback("/[a-z]+=([\'\"]).*?\\1/si", array($this, '_convert_attribute'), $str);
$str = preg_replace_callback("/<\w+.*?(?=>|<|$)/si", array($this, '_decode_entity'), $str);
其中_convert_attribute函數將匹配到的部分的'<','>','\\'轉換爲'>', '<', '\\\\'
protected function _convert_attribute($match)
{
return str_replace(array('>', '<', '\\'), array('>', '<', '\\\\'), $match[0]);
}
_decode_entity函數調用成員函數entity_decode進行實體解碼
public function entity_decode($str, $charset='UTF-8')
{
if (stristr($str, '&') === FALSE)
{
return $str;
}
$str = html_entity_decode($str, ENT_COMPAT, $charset);
$str = preg_replace('~&#x(0*[0-9a-f]{2,5})~ei', 'chr(hexdec("\\1"))', $str);
return preg_replace('~&#([0-9]{2,4})~e', 'chr(\\1)', $str);
}
⑥:再一次去除ASCII字符之間插入的空字符,如java\0script
$str = remove_invisible_characters($str);
⑦:將tabs轉換成' '
if (strpos($str, "\t") !== FALSE)
{
$str = str_replace("\t", ' ', $str);
}
⑧:去除不允許的字符:
$str = $this->_do_never_allowed($str);
⑨:去除PHP標籤:
if ($is_image === TRUE)
{
// Images have a tendency to have the PHP short opening and
// closing tags every so often so we skip those and only
// do the long opening tags.
$str = preg_replace('/<\?(php)/i', "<?\\1", $str);
}
else
{
$str = str_replace(array('<?', '?'.'>'), array('<?', '?>'), $str);
}
⑩:將字符串中的類似j a v a s c r i p t轉換爲javascript
$words = array(
'javascript', 'expression', 'vbscript', 'script', 'base64',
'applet', 'alert', 'document', 'write', 'cookie', 'window'
);
foreach ($words as $word)
{
$temp = '';
for ($i = 0, $wordlen = strlen($word); $i < $wordlen; $i++)
{
$temp .= substr($word, $i, 1)."\s*";
}
// We only want to do this when it is followed by a non-word character
// That way valid stuff like "dealer to" does not become "dealerto"
$str = preg_replace_callback('#('.substr($temp, 0, -3).')(\W)#is', array($this, '_compact_exploded_words'), $str);
}
⒒刪除無效的javascript鏈接和img標籤
do
{
$original = $str;
if (preg_match("/<a/i", $str))
{
$str = preg_replace_callback("#<a\s+([^>]*?)(>|$)#si", array($this, '_js_link_removal'), $str);
}
if (preg_match("/<img/i", $str))
{
$str = preg_replace_callback("#<img\s+([^>]*?)(\s?/?>|$)#si", array($this, '_js_img_removal'), $str);
}
if (preg_match("/script/i", $str) OR preg_match("/xss/i", $str))
{
$str = preg_replace("#<(/*)(script|xss)(.*?)\>#si", '[removed]', $str);
}
}
while($original != $str);
unset($original);
12.清除一些屬性:style, onclick and xmlns$str = $this->_remove_evil_attributes($str, $is_image);
13.將一些HTML元素轉換爲實體:
$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';
$str = preg_replace_callback('#<(/*\s*)('.$naughty.')([^><]*)([><]*)#is', array($this, '_sanitize_naughty_html'), $str);
14.清除一些腳本元素:
$str = preg_replace('#(alert|cmd|passthru|eval|exec|expression|system|fopen|fsockopen|file|file_get_contents|readfile|unlink)(\s*)\((.*?)\)#si', "\\1\\2(\\3)", $str);
15.最後的過濾:
$str = $this->_do_never_allowed($str);
最後返回$str