* This class contains some methods that can help you create secure applications and process input data securely.
* The address of CI official manual for this category: http://codeigniter.org.cn/user_guide/libraries/security.html
* Cross-site request protection cookie expiration time, the default is 2 hours (unit seconds)
' '
'' => ''
);
/* never allowed, regex replacement */
/**
* List of never allowed regex replacement
* List of disallowed regular replacement strings
* @var array
* @access protected
*/
protected $_never_allowed_regex = array(
'javascripts*:',
'expressions*((|()', // CSS and IE
'vbscripts*:', // IE, surprise!
'Redirects+302',
"(["'])?datas*:[^\1]*?base64[^\1]*?,[^\1]*?\1?"
);
/**
* Constructor
*
* @return void
*/
public function __construct()
{
// Is CSRF protection enabled?
// csrf 是否开启
if (config_item('csrf_protection') === TRUE)
{
// CSRF config 读取CSRF 配置并赋值给本类下的对应的属性
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
// 添加应用指定的cookie前缀
if (config_item('cookie_prefix'))
{
$this->_csrf_cookie_name = config_item('cookie_prefix').$this->_csrf_cookie_name;
}
// Set the CSRF hash
// 设置CSRF hash
$this->_csrf_set_hash();
}
log_message('debug', "Security Class Initialized");
}
// --------------------------------------------------------------------
/**
* Verify Cross Site Request Forgery Protection
* 验证跨站请求伪造保护
* @return object
*/
public function csrf_verify()
{
// If it's not a POST request we will set the CSRF cookie
// If it is not a post request, we need to 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 the request token does not exist, call csrf_show_error to report an error
if ( ! isset($_POST[$this->_csrf_token_name], $_COOKIE[$this->_csrf_cookie_name]))
{
$this->csrf_show_error();
} }
// Do the tokens match?
// If the token is incorrect, an error will be reported.
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
// pollute the _POST array
// Destroy the sign because we don’t want to pollute the _POST array
unset($_POST[$this->_csrf_token_name]);
// Nothing should last forever
// Destroy cookie name and reset hash and cookie
unset($_COOKIE[$this->_csrf_cookie_name]);
$this->_csrf_set_hash();
$this->csrf_set_cookie();
log_message('debug', 'CSRF token verified');
return $this;
}
//------------------------------------------------ -----------------------
/**
* Set Cross Site Request Forgery Protection Cookie
* Set fake cookies to protect cross-site requests
* @return object
*/
public function csrf_set_cookie()
{
$expire = time() + $this->_csrf_expire;
$secure_cookie = (config_item('cookie_secure') === TRUE) ? 1 : 0;
// Set cookie when https exists
if ($secure_cookie && (emptyempty($_SERVER['HTTPS']) OR strtolower($_SERVER['HTTPS']) === 'off'))
{
return FALSE;
} }
// Set cookie
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;
}
//------------------------------------------------ -----------------------
/**
* Show CSRF Error
* Show CSRF error
* @return void
*/
public function csrf_show_error()
{
show_error('The action you have requested is not allowed.');
}
// --------------------------------------------------------------------
/**
* Get CSRF Hash
* 获取CSRF hash
* Getter Method
*
* @return string self::_csrf_hash
*/
public function get_csrf_hash()
{
return $this->_csrf_hash;
}
// --------------------------------------------------------------------
/**
* Get CSRF Token Name
* Get CSRF order ranking
* Getter Method
*
* @return string self::csrf_token_name
*/
public function get_csrf_token_name()
{
return $this->_csrf_token_name;
}
// --------------------------------------------------------------------
/**
* XSS Clean
*
* Sanitizes data so that Cross Site Scripting Hacks can be
* prevented.Prevent This function does a fair amount of work but
* it is extremely thorough, designed to prevent even the
* most obscure XSS attempts. Nothing is ever 100% foolproof,
* of course, but I haven't been able to get anything passed
* the filter.
* Filter data to prevent cross-site scripting attacks. This function does some work, but it's very thorough,
* Even prevents most obscure XSS attempts. Of course, nothing is 100% safe,
* But we have done all we can think of in this filter.
*
* Note: This function should only be used to deal with data
* upon submission. It's not something that should
* be used for general runtime processing.
* Note: This function can only be used to process submitted data.
* This function should not be used during normal operation.
*
* This function was based in part on some code and ideas I
* got from Bitflux: http://channel.bitflux.ch/wiki/XSS_Prevention
*
* To help develop this script I used this great list of
* vulnerabilities along with a few other hacks I've
* harvested from examining vulnerabilities in other programs:
* http://ha.ckers.org/xss.html
*
* @param mixed string or array
* @param bool
* @return string
*/
public function xss_clean($str, $is_image = FALSE)
{
/*
* Is the string an array?
* 需要过滤的字符串是数组吗?
*
*/
if (is_array($str))
{
while (list($key) = each($str))
$str[$key] = $this->xss_clean($str[$key]);
}
return $str;
} }
/*
* Remove Invisible Characters
* Remove invisible characters
*/
$str = remove_invisible_characters($str);
// Validate Entities in URLs
// Verify the character entity in the URL
$str = $this->_validate_entities($str);
/*
* URL Decode
* URL decoding
* Just in case stuff like this is submitted:
* Prevent things like the following from being submitted
* *
* Note: Use rawurldecode() so it does not remove plus signs
* rawurldecode() does not decode the plus sign ('+') into a space, while urldecode() does.
* *
*/
$str = rawurldecode($str);
/*
* Convert character entities to ASCII
* Convert physical characters into ASCII code
* This makes our test below reliable, we only convert tags within entities because these are the entities that will cause security issues
* This permits our tests below to work reliably.
* We only convert entities that are within tags since
* these are the ones that will pose security problems.
* *
*/
$str = preg_replace_callback("/[a-z]+=(['"]).*?\1/si", array($this, '_convert_attribute'), $str);
$str = preg_replace_callback("/|<|$)/si", array($this, '_decode_entity'), $str);
/*
* Remove Invisible Characters Again!
* Remove invisible characters again
*/
$str = remove_invisible_characters($str);
/*
* Convert all tabs to spaces
* Convert all tab characters to spaces
* This prevents strings like this: ja vascript
* This is used to prevent strings similar to javascript
* NOTE: we deal with spaces between characters later.
* Note: We will deal with the spaces between characters later
* NOTE: preg_replace was found to be amazingly slow here on
* large blocks of data, so we use str_replace.
* Note: preg_replace is extremely slow here for large chunks of data, so use str_replace
* *
*/
if (strpos($str, "t") !== FALSE)
{
$str = str_replace("t", ' ', $str);
} }
/*
* Capture capture converted string for later comparison
* Capture the converted string for later comparison
*/
$converted_string = $str;
// Remove Strings that are never allowed
// Delete strings that are not allowed
$str = $this->_do_never_allowed($str);
/*
* Makes PHP tags safe
* Make PHP tags safe
* Note: XML tags are inadvertently replaced too:
* Note: XML tags can also be unintentionally replaced
*
* *
* But it doesn't seem to pose a problem.
* But it doesn’t seem to be a problem
*/
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);
} }
/*
* Compact any exploded words
* Compress all decomposed words
* This corrects words like: j a v a s c r i p t
* These words are compacted back to their correct state.
*/
$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*";
}
// 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);
} }
/*
* Remove disallowed Javascript in links or img tags
* Remove javascript code that is not allowed in link and image tags
* We used to do some version comparisons and use of stripos for PHP5,
* We usually use stripos in PHP5 to do some version comparisons,
* but it is dog slow compared to these simplified non-capturing
* But especially when the pattern exists in the string, it is much slower than the non-capturing preg_match()
* preg_match(), especially if the pattern exists in the string
*/
do
{
$original = $str;
$str = preg_replace_callback("#
]*?)(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);
// Remove evil attributes such as style, onclick and xmlns
// Remove harmful attributes, such as style, onclick, xmlns
$str = $this->_remove_evil_attributes($str, $is_image);
/*
* Sanitize naughty HTML elements
* Clean inappropriate HTML elements
* If a tag containing any of the words in the list
* below is found, the tag gets converted to entities.
* If a tag contains any of the words in the list below, the tag is converted to a character entity
* So this: