/system/core/Security.php 安全类
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 5.1.6 or newer
*
* @package CodeIgniter
* @author ExpressionEngine Dev Team
* @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
* @license http://codeigniter.com/user_guide/license.html
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
// ------------------------------------------------------------------------
/**
* Security Class
* 安全类
* @package CodeIgniter
* @subpackage Libraries
* @category Security
* @author ExpressionEngine Dev Team
* @link http://codeigniter.com/user_guide/libraries/security.html
*/
class CI_Security {
/**
* Random Hash for protecting URLs
* 随机Hash保护的URL
* @var string
* @access protected
*/
protected $_xss_hash = '';
/**
* Random Hash for Cross Site Request Forgery Protection Cookie
* 跨站点请求伪造保护曲奇随机Hash
* @var string
* @access protected
*/
protected $_csrf_hash = '';
/**
* Expiration time for Cross Site Request Forgery Protection Cookie
* Defaults to two hours (in seconds)
* *跨站点请求伪造保护Cookie的到期时间默认两个小时(秒)
* @var int
* @access protected
*/
protected $_csrf_expire = 7200;
/**
* Token name for Cross Site Request Forgery Protection Cookie
* 跨站点请求伪造保护曲奇令牌名称
* @var string
* @access protected
*/
protected $_csrf_token_name = 'ci_csrf_token';
/**
* Cookie name for Cross Site Request Forgery Protection Cookie
* 跨站点请求伪造保护曲奇Cookie名称
* @var string
* @access protected
*/
protected $_csrf_cookie_name = 'ci_csrf_token';
/**
* List of never allowed strings
* 决不允许字符串列表
* @var array
* @access protected
*/
protected $_never_allowed_str = array(
'document.cookie' => '[removed]',
'document.write' => '[removed]',
'.parentNode' => '[removed]',
'.innerHTML' => '[removed]',
'window.location' => '[removed]',
'-moz-binding' => '[removed]',
'<!--' => '<!--',
'-->' => '-->',
'<![CDATA[' => '<![CDATA[',
'<comment>' => '<comment>'
);
/* never allowed, regex replacement 绝不允许,正则表达式替换*/
/**
* List of never allowed regex replacement
* 正则表达式替换决不允许列表
* @var array
* @access protected
*/
protected $_never_allowed_regex = array(
'javascript\s*:',
'expression\s*(\(|&\#40;)', // CSS and IE
'vbscript\s*:', // IE, surprise!
'Redirect\s+302',
"([\"'])?data\s*:[^\\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哈希
$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
// 如果它不是一个POST请求,我们将设置CSRF饼干
// REQUEST_METHOD 设置不为POST
if (strtoupper($_SERVER['REQUEST_METHOD']) !== 'POST')
{
return $this->csrf_set_cookie();
}
// Do the tokens exist in both the _POST and _COOKIE arrays?
// 令牌存在彦博和_COOKIE数组?
//操作,这里的isset咱能这么写呢,
//哦,意思是在$POST或者_COOKIE中都不存在时
if ( ! isset($_POST[$this->_csrf_token_name], $_COOKIE[$this->_csrf_cookie_name]))
{
$this->csrf_show_error();
}
// Do the tokens match?
// 做令牌比赛?...
// 如果post 与cookie中的值不相等也显示错误
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
// 我们杀了这一点,因为我们做了,我们不想
// polute_POST数组
// 删除POST数组中的值
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 CSRF令牌验证');
return $this;
}
// --------------------------------------------------------------------
/**
* Set Cross Site Request Forgery Protection Cookie
* 设置跨站点请求伪造保护曲奇
* @return object
*/
public function csrf_set_cookie()
{
$expire = time() + $this->_csrf_expire; //当前时间表加上过期时间表
$secure_cookie = (config_item('cookie_secure') === TRUE) ? 1 : 0;
//默认设置为cookie_secure==false
//$_SERVER['HTTPS'] 如果通过https访问,则被设为一个非空的值(on),否则返回off
if ($secure_cookie && (empty($_SERVER['HTTPS']) OR strtolower($_SERVER['HTTPS']) === 'off'))
{
return FALSE;
}
//设置COOKIE
//$this->_csrf_cookie_name cookie的名称
//$this->_csrf_hash 跨站点请求伪造保护曲奇随机Hash
//$expire 过期时间
//config_item('cookie_path') cookie的路径
//config_item('cookie_domain') 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 的CRSF cookie集");
return $this;
}
// --------------------------------------------------------------------
/**
* Show CSRF Error
* 显示CSRF错误
* @return void
*/
public function csrf_show_error()
{
show_error('The action you have requested is not allowed. 您所要求的行动是不允许的');
}
// --------------------------------------------------------------------
/**
* Get CSRF Hash
* CSRF哈希
*
* Getter Method
* getter方法
*
* @return string self::_csrf_hash
*/
public function get_csrf_hash()
{
return $this->_csrf_hash;
}
// --------------------------------------------------------------------
/**
* Get CSRF Token Name
* CSRF令牌名称
*
* Getter Method
* getter方法
*
* @return string self::csrf_token_name
*/
public function get_csrf_token_name()
{
return $this->_csrf_token_name;
}
// --------------------------------------------------------------------
/**
* XSS Clean
* XSS清洁
*
* Sanitizes data so that Cross Site Scripting Hacks can be
* prevented. 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.
*
* 清理数据,因此,跨站点脚本黑客可以防止。此功能做了相当多的工作,但
* 这是非常彻底的,旨在防止甚至
* 最不起眼的的XSS尝试。没有什么是永远100%万无一失,
* 当然,但我没有能够得到任何东西通过过滤器。
*
*
* 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.
* 注:此功能只应该用来处理数据后提交。这是不是应该用于一般运行时处理。
*
*
* 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
* 删除不可见字符 这个函数是自定义的
*/
$str = remove_invisible_characters($str);
// Validate Entities in URLs
// 在URL验证实体
$str = $this->_validate_entities($str);
/*
* URL Decode
* URL解码
* Just in case stuff like this is submitted:
* 提交以防万一,这样的东西:
*
* <a href="http://%77%77%77%2E%67%6F%6F%67%6C%65%2E%63%6F%6D">Google</a>
*
* Note: Use rawurldecode() so it does not remove plus signs
* 注:使用rawurldecode(),所以它不会删除加号
*/
$str = rawurldecode($str);
//rawurldecode() 译编url编码字符串
//将一连串百份比符号(%)后面跟随二个迷惑的数字的字符串,照其字面上的意义将它译解,并传回译编后的字符串
//foo%20bar%40baz
//译解成foo bar@baz
/*
* Convert character entities to ASCII
* 转换为ASCII字符实体
*
* 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("/<\w+.*?(?=>|<|$)/si", array($this, '_decode_entity'), $str);
/*
* Remove Invisible Characters Again!
* 再次移除不可见字符!
*/
$str = remove_invisible_characters($str);
/*
* Convert all tabs to spaces
* 将所有的制表符为空格
*
* This prevents strings like this: ja vascript
* NOTE: we deal with spaces between characters later.
* NOTE: preg_replace was found to be amazingly slow here on
* large blocks of data, so we use str_replace.
* 防止这样的字符串:JA vascript的
* 注意:我们之间的空格字符后处理。
* 注意:preg_replace函数被认为是这里令人惊讶的慢
* 大的数据块,所以我们用str_replace函数。
*/
//如果存在制表符,那么直接全部替换为空格
if (strpos($str, "\t") !== FALSE)
{
$str = str_replace("\t", ' ', $str);
}
/*
* Capture converted string for later comparison
* 捕获转换的字符串后比较
*/
$converted_string = $str;
// Remove Strings that are never allowed
// 决不允许删除字符串
$str = $this->_do_never_allowed($str);
/*
* Makes PHP tags safe
* 使PHP标签的安全
* Note: XML tags are inadvertently replaced too:
* 注:XML标签无意中替换过:
*
* <?xml
*
* But it doesn't seem to pose 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.
// 图像有一种倾向,有PHP的开幕式和短
// 结束标记,每隔一段时间,所以我们跳过那些只
// 做长期开放标签。
$str = preg_replace('/<\?(php)/i', "<?\\1", $str);
}
else
{
$str = str_replace(array('<?', '?'.'>'), array('<?', '?>'), $str);
}
/*
* Compact any exploded words
* 紧凑任何爆炸的话
*
* This corrects words like: j a v a s c r i p t
* These words are compacted back to their correct state.
* 纠正的话,如:J A V A S C R I P T
* 这些话被压缩到其正确的状态。
*/
$words = array(
'javascript', 'expression', 'vbscript', 'script', 'base64',
'applet', 'alert', 'document', 'write', 'cookie', 'window'
);
foreach ($words as $word)
{
$temp = '';
//将这些字符串中的每个字符后面都加上\s*
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"
// 我们只希望这样做时,它后面是一个非单词字符
// 这样,有效的东西,如“经销商”不成为“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
* We used to do some version comparisons and use of stripos for PHP5,
* but it is dog slow compared to these simplified non-capturing
* preg_match(), especially if the pattern exists in the string
*
* 不允许删除链接或JavaScript中的img标签
* 我们用来做一些版本比较,stripos函数使用PHP5,,但它是狗放缓相比,这些简化非捕获
* preg_match()函数,特别是如果该图案在字符串中存在
*
*/
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);
// Remove evil attributes such as style, onclick and xmlns
// 删除邪恶的属性,如风格,onclick和XMLNS
$str = $this->_remove_evil_attributes($str, $is_image);
/*
* Sanitize naughty HTML elements
* 消毒调皮的HTML元素
*
* If a tag containing any of the words in the list
* below is found, the tag gets converted to entities.
* 如果标记包含在列表中的任何字
* 下面被发现,该标签被转换为实体。
* So this: <blink>
* Becomes: <blink>
*/
$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);
/*
* Sanitize naughty scripting elements
* 消毒顽皮的脚本元素
*
* Similar to above, only instead of looking for
* tags it looks for PHP and JavaScript commands
* that are disallowed. Rather than removing the
* code, it simply converts the parenthesis to entities
* rendering the code un-executable.
* *与上述类似,而不是只寻找标签它看起来PHP和JavaScript命令是不允许的。
* 而不是删除代码,它只是括号实体转换渲染代码未可执行。
* For example: eval('some code')
* Becomes: eval('some code')
*/
$str = preg_replace('#(alert|cmd|passthru|eval|exec|expression|system|fopen|fsockopen|file|file_get_contents|readfile|unlink)(\s*)\((.*?)\)#si', "\\1\\2(\\3)", $str);
// Final clean up
// This adds a bit of extra precaution in case
// something got through the above filters
// 最后的清理
// 这增添了几分额外的预防措施的情况下
// 通过上面的过滤器/ /东西了
$str = $this->_do_never_allowed($str);
/*
* Images are Handled in a Special Way
* - Essentially, we want to know that after all of the character
* conversion is done whether any unwanted, likely XSS, code was found.
* If not, we return TRUE, as the image is clean.
* However, if the string post-conversion does not matched the
* string post-removal of XSS, then it fails, as there was unwanted XSS
* code found and removed/changed during processing.
* *图像处理一种特殊的方式
* - 从本质上讲,我们想知道,毕竟字符
* 转换做任何不必要的,可能XSS,代码是否被发现。
* 如果没有,我们返回TRUE,作为图像是干净的。
* 但是,如果该字符串转换后的不匹配
* 字符串后去除XSS,那么它失败了,因为不必要的XSS
* 代码找到并删除/更改在处理过程中。
*
*/
if ($is_image === TRUE)
{
return ($str == $converted_string) ? TRUE: FALSE;
}
log_message('debug', "XSS Filtering completed XSS过滤完成");
return $str;
}
// --------------------------------------------------------------------
/**
* Random Hash for protecting URLs
* 随机Hash保护的URL
* @return string
*/
public function xss_hash()
{
//如果_xss_hadn为空值的庆
if ($this->_xss_hash == '')
{
mt_srand(); //mt_srand()好像php5可以直接用rand了,这个应该是为了兼容老版本
$this->_xss_hash = md5(time() + mt_rand(0, 1999999999));
}
return $this->_xss_hash;
}
// --------------------------------------------------------------------
/**
* HTML Entities Decode
* HTML实体解码
*
* This function is a replacement for html_entity_decode()
* 这个函数是一个更换html_entity_decode()
*
* The reason we are not using html_entity_decode() by itself is because
* while it is not technically correct to leave out the semicolon
* at the end of an entity most browsers will still interpret the entity
* correctly. html_entity_decode() does not convert entities without
* semicolons, so we are left with our own little solution here. Bummer.
*
* 我们之所以不使用html_entity_decode()本身是因为,而它在技术上并不正确离开了分号,
* 结尾一个实体大多数浏览器仍然会解释实体正确。 html_entity_decode()不无实体转换分号,
* 所以我们只剩下我们自己的解决方案,在这里。令人失望。
* @param string
* @param string
* @return string
*/
public function entity_decode($str, $charset='UTF-8')
{
//如果没有&连接字符
if (stristr($str, '&') === FALSE)
{
return $str;
}
//html_entity_decode() 函数把 HTML 实体转换为字符。
//ENT_COMPAT - 默认。仅解码双引号。
//ENT_QUOTES - 解码双引号和单引号。
//ENT_NOQUOTES - 不解码任何引号。
$str = html_entity_decode($str, ENT_COMPAT, $charset);
//真看不错啊,反正是替换chr(hexdec(1))
$str = preg_replace('~&#x(0*[0-9a-f]{2,5})~ei', 'chr(hexdec("\\1"))', $str);
//chr(1)
return preg_replace('~&#([0-9]{2,4})~e', 'chr(\\1)', $str);
}
// --------------------------------------------------------------------
/**
* Filename Security
* 文件名安全
* @param string
* @param bool
* @return string
*/
public function sanitize_filename($str, $relative_path = FALSE)
{
$bad = array(
"../",
"<!--",
"-->",
"<",
">",
"'",
'"',
'&',
'$',
'#',
'{',
'}',
'[',
']',
'=',
';',
'?',
"%20",
"%22",
"%3c", // <
"%253c", // <
"%3e", // >
"%0e", // >
"%28", // (
"%29", // )
"%2528", // (
"%26", // &
"%24", // $
"%3f", // ?
"%3b", // ;
"%3d" // =
);
if ( ! $relative_path)
{
$bad[] = './';
$bad[] = '/';
}
$str = remove_invisible_characters($str, FALSE);
return stripslashes(str_replace($bad, '', $str));
}
// ----------------------------------------------------------------
/**
* Compact Exploded Words
* 紧凑型引爆词
* Callback function for xss_clean() to remove whitespace from
* things like j a v a s c r i p t
* 回调函数xss_clean()删除空白的东西,像J A V A R I S C P T
* @param type
* @return type
*/
protected function _compact_exploded_words($matches)
{
return preg_replace('/\s+/s', '', $matches[1]).$matches[2];
}
// --------------------------------------------------------------------
/*
* Remove Evil HTML Attributes (like evenhandlers and style)
* 卸下邪恶的HTML属性(如evenhandlers和风格)
*
*
* It removes the evil attribute and either:
* 消除邪恶属性:
*
* - Everything up until a space 一切,直到空间
*
* For example, everything between the pipes:
* 例如,管道之间的一切:
* <a |style=document.write('hello');alert('world');| class=link>
* - Everything inside the quotes 引号内的一切
* For example, everything between the pipes:
* 例如,管道之间的一切:
* <a |style="document.write('hello'); alert('world');"| class="link">
*
* @param string $str The string to check 要检查的字符串
* @param boolean $is_image TRUE if this is an image TRUE,如果这是一个图像
* @return string The string with the evil attributes removed 与邪恶的属性去掉串的字符串
*/
protected function _remove_evil_attributes($str, $is_image)
{
// All javascript event handlers (e.g. onload, onclick, onmouseover), style, and xmlns
// 所有的JavaScript事件处理程序(如onload事件的onclick,onmouseover事件),风格,和xmlns
$evil_attributes = array('on\w*', 'style', 'xmlns', 'formaction');
if ($is_image === TRUE)
{
/*
* Adobe Photoshop puts XML metadata into JFIF images,
* including namespacing, so we have to allow this for images.
* * Adobe Photoshop中把XML元数据JFIF图像,
* 包括命名空间,所以我们必须让这个图像。
*
*/
//array_search() 函数与 in_array() 一样,在数组中查找一个键值。如果找到了该值,匹配元素的键名会被返回。
// array_search('xmlns', $evil_attributes)
unset($evil_attributes[array_search('xmlns', $evil_attributes)]);
}
do {
$count = 0;
$attribs = array();
// find occurrences of illegal attribute strings without quotes
// 出现非法属性字符串不带引号
preg_match_all('/('.implode('|', $evil_attributes).')\s*=\s*([^\s>]*)/is', $str, $matches, PREG_SET_ORDER);
foreach ($matches as $attr)
{
//preg_quote
//preg_quote()需要参数 str 并向其中 每个正则表达式语法中的字符前增加一个反斜线。 这通常用于你有一些运行时字符串 需要作为正则表达式进行匹配的时候。
//正则表达式特殊字符有: . \ + * ? [ ^ ] $ ( ) { } = ! < > | : -
$attribs[] = preg_quote($attr[0], '/');
}
// find occurrences of illegal attribute strings with quotes (042 and 047 are octal quotes)
// 找到出现的非法属性字符串引号(042和047是八进制报价)
preg_match_all("/(".implode('|', $evil_attributes).")\s*=\s*(\042|\047)([^\\2]*?)(\\2)/is", $str, $matches, PREG_SET_ORDER);
foreach ($matches as $attr)
{
$attribs[] = preg_quote($attr[0], '/');
}
// replace illegal attribute strings that are inside an html tag
// 替换HTML标签内的非法属性字符串
if (count($attribs) > 0)
{
$str = preg_replace("/<(\/?[^><]+?)([^A-Za-z<>\-])(.*?)(".implode('|', $attribs).")(.*?)([\s><])([><]*)/i", '<$1 $3$5$6$7', $str, -1, $count);
}
} while ($count);
return $str;
}
// --------------------------------------------------------------------
/**
* Sanitize Naughty HTML
* 消毒淘气的HTML
* Callback function for xss_clean() to remove naughty HTML elements
* 回调函数xss_clean的()删除顽皮的HTML元素
* @param array
* @return string
*/
protected function _sanitize_naughty_html($matches)
{
// encode opening brace
// 编码左括号
$str = '<'.$matches[1].$matches[2].$matches[3];
// encode captured opening or closing brace to prevent recursive vectors
// 编码捕获打开或关闭支撑,以防止递归向量
$str .= str_replace(array('>', '<'), array('>', '<'),
$matches[4]);
return $str;
}
// --------------------------------------------------------------------
/**
* JS Link Removal
* JS链接删除
*
* Callback function for xss_clean() to sanitize links
* This limits the PCRE backtracks, making it more performance friendly
* and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in
* PHP 5.2+ on link-heavy strings
* 回调函数为xss_clean()消毒链接
* 此限制的的PCRE回溯,使性能更友好
* 防止PREG_BACKTRACK_LIMIT_ERROR的被触发
* PHP5.2+链接沉重的字符串
* @param array
* @return string
*/
protected function _js_link_removal($match)
{
return str_replace(
$match[1],
preg_replace(
'#href=.*?(alert\(|alert&\#40;|javascript\:|livescript\:|mocha\:|charset\=|window\.|document\.|\.cookie|<script|<xss|data\s*:)#si',
'',
$this->_filter_attributes(str_replace(array('<', '>'), '', $match[1]))
),
$match[0]
);
}
// --------------------------------------------------------------------
/**
* JS Image Removal
* JS图片删除
* Callback function for xss_clean() to sanitize image tags
* This limits the PCRE backtracks, making it more performance friendly
* and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in
* PHP 5.2+ on image tag heavy strings
* 回调函数为xss_clean()消毒图像标签
* 此限制的的PCRE回溯,使性能更友好
* 防止PREG_BACKTRACK_LIMIT_ERROR的被触发
* PHP5.2+对图像标记重字符串
* @param array
* @return string
*/
protected function _js_img_removal($match)
{
return str_replace(
$match[1],
preg_replace(
'#src=.*?(alert\(|alert&\#40;|javascript\:|livescript\:|mocha\:|charset\=|window\.|document\.|\.cookie|<script|<xss|base64\s*,)#si',
'',
$this->_filter_attributes(str_replace(array('<', '>'), '', $match[1]))
),
$match[0]
);
}
// --------------------------------------------------------------------
/**
* Attribute Conversion
* 属性转换
* Used as a callback for XSS Clean
* 用于XSS清洁作为回调...
* @param array
* @return string
*/
protected function _convert_attribute($match)
{
//将> < \\替换为一些html的实体
return str_replace(array('>', '<', '\\'), array('>', '<', '\\\\'), $match[0]);
}
// --------------------------------------------------------------------
/**
* Filter Attributes
* 过滤器属性
* Filters tag attributes for consistency and safety
* 过滤器标签属性的一致性和安全性
* @param string
* @return string
*/
protected function _filter_attributes($str)
{
$out = '';
if (preg_match_all('#\s*[a-z\-]+\s*=\s*(\042|\047)([^\\1]*?)\\1#is', $str, $matches))
{
foreach ($matches[0] as $match)
{
$out .= preg_replace("#/\*.*?\*/#s", '', $match);
}
}
return $out;
}
// --------------------------------------------------------------------
/**
* HTML Entity Decode Callback
* HTML实体译码回调
* Used as a callback for XSS Clean
* 用于XSS清洁作为回调
* @param array
* @return string
*/
protected function _decode_entity($match)
{
//config_item('charset') 当前的编码方式
return $this->entity_decode($match[0], strtoupper(config_item('charset')));
}
// --------------------------------------------------------------------
/**
* Validate URL entities
* 验证URL实体
* Called by xss_clean()
*
* @param string
* @return string
*/
protected function _validate_entities($str)
{
/*
* Protect GET variables in URLs
* 保护GET URL中的变量
*/
// 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.
* 添加一个分号,如果失踪。我们这样做是为了使转换的实体为ASCII。
*/
$str = preg_replace('#(&\#?[0-9a-z]{2,})([\x00-\x20])*;?#i', "\\1;\\2", $str);
/*
* Validate UTF16 two byte encoding (x00)
* 验证UTF16两个字节编码(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
* 未保护GET URL中的变量
*/
$str = str_replace($this->xss_hash(), '&', $str);
return $str;
}
// ----------------------------------------------------------------------
/**
* Do Never Allowed
* 不要决不允许
* A utility function for xss_clean()
* 为xss_clean效用函数()
* @param string
* @return string
*/
//删除那些决不允许存在的字符串或者正则表达式
protected function _do_never_allowed($str)
{
$str = str_replace(array_keys($this->_never_allowed_str), $this->_never_allowed_str, $str);
foreach ($this->_never_allowed_regex as $regex)
{
$str = preg_replace('#'.$regex.'#is', '[removed]', $str);
}
return $str;
}
// --------------------------------------------------------------------
/**
* Set Cross Site Request Forgery Protection Cookie
* 设置跨站点请求伪造保护曲奇
* @return string
*/
protected function _csrf_set_hash()
{
if ($this->_csrf_hash == '')
{
// If the cookie exists we will use it's value.
// 如果cookie存在,我们将使用它的价值。
// 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
// 造成此功能失败的子页面
// preg_match('#^[0-9a-f]{32}$#iS', $_COOKIE[$this->_csrf_cookie_name])
//int preg_match( string pattern, string subject [, array matches [, int flags]] )
//在 subject 字符串中搜索与pattern给出的正则表达式相匹配的内容。
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;
}
}
/* End of file Security.php */
/* Location: ./system/libraries/Security.php */
没看太懂,说真的,好多正则,真是看不懂,感觉自己还在小学行走。。。
语法能理解,但正则伤心啊

浙公网安备 33010602011771号