codeigniter源代码分析 -安全类 Security.php

本文深入剖析了CI框架中的安全组件,重点介绍了其核心方法xss_clean的工作原理及内部实现细节,包括实体编码调整、HTML实体解码、关键词过滤等步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Security 安全类主要是对 url 内容进行 xss 攻击的过滤

很多匹配格式 建议阅读之前先巩固下正则的知识

主要的 xss_clear 方法 其中的处理流程如下:

_validate_entities  对url进行实体编码的调整

_convert_attribute 对标签 属性=值 形式字符串中的 < > \ 字符进行实体转换

_decode_entity 对HTML实体解码 实体转换成字符 解决php函数不能解码10进制形式的HTML实体的问题(这里解码是为了更方便的对数据进行匹配处理)

_do_never_allowed 永远不允许的关键词 过滤掉

转义 <?php 

_compact_exploded_words 将关键词中间的空格去除


do

       _js_link_removel ->_filter_attributes 

      _js_img_removal ->_filter_attributes

标签里面的 属性 href src 中出现可执行脚本代码 将属性带代码一同干掉

filter_attributes 是去除里面的注释部分

while()


remove_evil_attributes 去除事件里面的脚本代码

_sanitize_naughty_html 对html中的编码实体化 (之前解码为了处理方便 处理完毕再编码到实体)

_do_never_allowed 同上

下面是源码and注释

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class CI_Security {

	protected $_xss_hash			= '';
	protected $_csrf_hash			= '';
	protected $_csrf_expire			= 7200;
	protected $_csrf_token_name		= 'ci_csrf_token';
	protected $_csrf_cookie_name	= 'ci_csrf_token';
	//用 val 代替 key
	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>'
	);
	//用[removed]代替 key作为正则匹配到的部分
	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?"
	);
	public function __construct()
	{
		if (config_item('csrf_protection') === TRUE)
		{
			foreach (array('csrf_expire', 'csrf_token_name', 'csrf_cookie_name') as $key)
			{
				if (FALSE !== ($val = config_item($key)))
				{
					$this->{'_'.$key} = $val;
				}
			}
			if (config_item('cookie_prefix'))
			{
				$this->_csrf_cookie_name = config_item('cookie_prefix').$this->_csrf_cookie_name;
			}
			// 为csrf生成hash串
			$this->_csrf_set_hash();
		}

		log_message('debug', "Security Class Initialized");
	}
	// 验证csrf
	public function csrf_verify()
	{
		if (strtoupper($_SERVER['REQUEST_METHOD']) !== 'POST')
		{ //请求方式非POST 设置csrf csrf 是对POST请求进行的验证
			return $this->csrf_set_cookie();
		}
		if ( ! isset($_POST[$this->_csrf_token_name], $_COOKIE[$this->_csrf_cookie_name]))
		{
			$this->csrf_show_error(); // form表单的csrf 跟cookie里面的csrf都为空
		}
		if ($_POST[$this->_csrf_token_name] != $_COOKIE[$this->_csrf_cookie_name])
		{
			$this->csrf_show_error(); //两个csrf的值不相等
		}
		//去除csrf
		unset($_POST[$this->_csrf_token_name]);
		unset($_COOKIE[$this->_csrf_cookie_name]);
		// 重新生成csrf hash 并发送cookie
		$this->_csrf_set_hash();
		$this->csrf_set_cookie();
		log_message('debug', 'CSRF token verified');
		return $this;
	}
	// csrf添加到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; //是否经过 https
		}
		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;
	}
	public function csrf_show_error()
	{
		show_error('The action you have requested is not allowed.');
	}
	public function get_csrf_hash()
	{
		return $this->_csrf_hash;
	}
	public function get_csrf_token_name()
	{
		return $this->_csrf_token_name;
	}

	// --------------------------------------------------------------------

	/**
	 * XSS Clean
	 *
	 * 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.
	 *
	 * 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)
	{
		if (is_array($str))
		{
			while (list($key) = each($str))
			{
				$str[$key] = $this->xss_clean($str[$key]);
			}
			return $str;
		}
		// 去除无法显示的字符 
		$str = remove_invisible_characters($str);
		// 过滤实体
		$str = $this->_validate_entities($str);
		$str = rawurldecode($str);//对URL进行解码
		// 过滤HTML标签属性特别是属性值 匹配到 attr='val' or attr="val" 的形式 
		$str = preg_replace_callback("/[a-z]+=([\'\"]).*?\\1/si", array($this, '_convert_attribute'), $str);
		//解码 实体
		// ?= 零宽先行断言 匹配后面表达式前面的位置 表达式开始位置
		$str = preg_replace_callback("/<\w+.*?(?=>|<|$)/si", array($this, '_decode_entity'), $str);
		$str = remove_invisible_characters($str);
		if (strpos($str, "\t") !== FALSE)
		{
			$str = str_replace("\t", ' ', $str);//空格代替 \t
		}
		$converted_string = $str;
		// 替换掉关键字
		$str = $this->_do_never_allowed($str);
		if ($is_image === TRUE)
		{
			// 转义php脚本格式的数据 对 <?php 中的 '<' 转义成 <
			$str = preg_replace('/<\?(php)/i', "<?\\1", $str);
		}
		else
		{	//转义XML格式的数据格式
			$str = str_replace(array('<?', '?'.'>'),  array('<?', '?>'), $str);
		}
		$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++)
			{
				// 通过words形成 j\s*a\s*v\s*a\s*s\s*c\s*r\s*i\s*p\s*t\s*
				$temp .= substr($word, $i, 1)."\s*";
			}
			// 先 substr($temp,0,-3) 去掉 words中最后三个字符  '\s*'
			// 匹配到任意中间空格的关键字 然后callback函数去除关键字中间的空格
			// 防止用关键字中间空格 伪造出脚本
			$str = preg_replace_callback('#('.substr($temp, 0, -3).')(\W)#is', array($this, '_compact_exploded_words'), $str);
		}
		do
		{
			$original = $str;

			if (preg_match("/<a/i", $str))
			{
				// 匹配到a标签
				$str = preg_replace_callback("#<a\s+([^>]*?)(>|$)#si", array($this, '_js_link_removal'), $str);
			}
			if (preg_match("/<img/i", $str))
			{
				// 匹配到img标签
				$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))
			{
				// 匹配到脚本script标签
				$str = preg_replace("#<(/*)(script|xss)(.*?)\>#si", '[removed]', $str);
			}
		}
		while($original != $str);//过滤不干净就继续过滤
		unset($original);
		//移除事件属性
		$str = $this->_remove_evil_attributes($str, $is_image);
		$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';
										// 1         2           3      4
		$str = preg_replace_callback('#<(/*\s*)('.$naughty.')([^><]*)([><]*)#is', array($this, '_sanitize_naughty_html'), $str);
		// 过滤函数调用 eval()、alert()、cmd()、... 将 ( ) 转义成 HTML 十进制代码
		$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
		$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.
		 */

		if ($is_image === TRUE)
		{
			return ($str == $converted_string) ? TRUE: FALSE;
		}

		log_message('debug', "XSS Filtering completed");
		return $str;
	}
	public function xss_hash()
	{
		// 生成hash
		if ($this->_xss_hash == '')
		{
			mt_srand();
			$this->_xss_hash = md5(time() + mt_rand(0, 1999999999));
		}
		return $this->_xss_hash;
	}
	// html_entity_decode 将html实体转换成字符串 但是它不能对HTML十进制形式转换
	public function entity_decode($str, $charset='UTF-8')
	{
		if (stristr($str, '&') === FALSE)
		{
			return $str;//不需要解码
		}
		// 下面解决不能转换的问题
		$str = html_entity_decode($str, ENT_COMPAT, $charset);
		// hexdec 将十六进制转换为十进制
		// 将HTML实体编码 &#XX 中 XX 部分的十六进制转换为十进制
		$str = preg_replace('~&#x(0*[0-9a-f]{2,5})~ei', 'chr(hexdec("\\1"))', $str);
		//&#xx HTML实体 XX 转换为对应的字符
		return preg_replace('~&#([0-9]{2,4})~e', 'chr(\\1)', $str);
	}

	/*
	去除文件名中不合法的字符 并且对一些字符转义
*/
	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));
	}
	protected function _compact_exploded_words($matches)
	{//剔除1中的空格
		return preg_replace('/\s+/s', '', $matches[1]).$matches[2];
	}
	protected function _remove_evil_attributes($str, $is_image)
	{
		// 所有有on开头的属性
		$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.
			 */
			unset($evil_attributes[array_search('xmlns', $evil_attributes)]);
		}

		do {
			$count = 0;
			$attribs = array();

			// find attribute strings with quotes (042 and 047 are octal quotes 八进制引号)
			// 匹配带引号的属性 042 047 八进制引号 e.g. attr='value'
			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], '/');
			}
			// find attribute strings without quotes
			// 匹配 不 带引号的属性 e.g. attr=value
			preg_match_all('/('.implode('|', $evil_attributes).')\s*=\s*([^\s>]*)/is', $str, $matches, PREG_SET_ORDER);
			foreach ($matches as $attr)
			{
				$attribs[] = preg_quote($attr[0], '/');
			}
			// 去除字符串中HTML标签里面的 这种 onclick = 'javascript:func();'
			if (count($attribs) > 0)
			{
								    // 1       2            3         4               5                6      7       8
				$str = preg_replace('/(<?)(\/?[^><]+?)([^A-Za-z<>\-])(.*?)('.implode('|', $attribs).')(.*?)([\s><]?)([><]*)/i', '$1$2 $4$6$7$8', $str, -1, $count);
			}

		} while ($count);
		return $str;
	}
	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;
	}
	protected function _js_link_removal($match)
	{
		return str_replace(
			$match[1], // match[1]里面是属性
			preg_replace(// 如果a标签的href值是危险的内容 将href带值一起干掉
				'#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]
		);
	}
	protected function _js_img_removal($match)
	{
		return str_replace(
			$match[1],
			preg_replace(//去除 img 标签属性
				'#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]
		);
	}
	/*
		将字符串中的 > < \ 三个字符转换成HTML实体
		防范<a href='<?php phpcode ...;?>'> 这样嵌入php代码的xss攻击形式
	*/
	protected function _convert_attribute($match)
	{
		return str_replace(array('>', '<', '\\'), array('>', '<', '\\\\'), $match[0]);
	}
	protected function _filter_attributes($str)
	{
		$out = '';

		// 匹配 attr = 'val' or attr = "val"
		if (preg_match_all('#\s*[a-z\-]+\s*=\s*(\042|\047)([^\\1]*?)\\1#is', $str, $matches))
		{
			foreach ($matches[0] as $match)
			{
				//  去除 里面的注释 /*some*/
				$out .= preg_replace("#/\*.*?\*/#s", '', $match);
			}
		}

		return $out;
	}
	protected function _decode_entity($match)
	{
		return $this->entity_decode($match[0], strtoupper(config_item('charset')));
	}
	// 过滤URL实体
	/*
		get方式传递HTML十进制编码 &#XX; 
		& # ; 这些是url中的保留关键字 传递不过去的
		我们可以对其进行uriencode --> %26%23XX%3b
	*/
	protected function _validate_entities($str)
	{
		// &var=val --> xss_hash+var=val 起到保护作用
		$str = preg_replace('|\&([a-z\_0-9\-]+)\=([a-z\_0-9\-]+)|i', $this->xss_hash()."\\1=\\2", $str);
		// 十进制HTML实体表示
		// \x00-\x20 --> ASCII 0-32 不能直接显示的字符 如果有不能显示的字符将他移动到 ';' 后面
		$str = preg_replace('#(&\#?[0-9a-z]{2,})([\x00-\x20])*;?#i', "\\1;\\2", $str);
		/*
		 * Validate UTF16 two byte encoding (x00)
		 */
		$str = preg_replace('#(&\#x?)([0-9A-F]+);?#i',"\\1\\2;",$str);

		// 又把xss_hash 替换成了& 实现保护作用 因为中间的处理有 & 符号
		$str = str_replace($this->xss_hash(), '&', $str);

		return $str;
	}
	// 替换字符串中绝对不允许出现的字符串组合
	// 防止与HTML实体组合构造出标签进行xss攻击
	protected function _do_never_allowed($str)
	{//val replace the key
		$str = str_replace(array_keys($this->_never_allowed_str), $this->_never_allowed_str, $str);

		foreach ($this->_never_allowed_regex as $regex)
		{//match and replaced by [removed]
			$str = preg_replace('#'.$regex.'#is', '[removed]', $str);
		}

		return $str;
	}
	protected function _csrf_set_hash()
	{
		if ($this->_csrf_hash == '')
		{
			//csrf 已经存在在cookie里面 对属性_csrf_hash进行一次赋值返回
			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;
	}
}

Code Tips:

主要是正则的写法 以及各种xss的攻击形式以防范策略

这个安全类是CI中(DB还没看)最大的一个类了把


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值