如何php防止XSS攻击
什么是XSS:这里通俗的讲,就像是SQL注入一样,XSS攻击也可以算是对HTML和JS的一种注入。你本来希望得到是从用户那得到一段有用的文本文字,但用户提交给你的却是别有用心的可执行javascript或者其他脚本,当你再把这些提交的内容显示到页面上时,xss攻击就发生了。
关于xss的攻击方式和场景层出不穷,以下是一些解决的方法,各位可以借鉴,如果有不准确的在下方评论,忘各位大神Coder不吝赐教
方法一
PHP htmlentities()函数 ,htmlentities() 函数把字符转换为 HTML 实体。语法为htmlentities(string,flags,character-set,double_encode)
实例把一些字符转换成HTML实体
- <?php
- $str = "Jane & 'Tarzan'";
- echo htmlentities($str, ENT_COMPAT); // Will only convert double quotes
- echo "<br>";
- echo htmlentities($str, ENT_QUOTES); // Converts double and single quotes
- echo "<br>";
- echo htmlentities($str, ENT_NOQUOTES); // Does not convert any quotes
- ?>
上面代码的 HTML 输出如下(查看源代码):
- <!DOCTYPE html>
- <html>
- <body>
- Jane & 'Tarzan'<br>
- Jane & 'Tarzan'<br>
- Jane & 'Tarzan'
- </body>
- </html>
上面代码的浏览器输出如下
Jane & 'Tarzan'
Jane & 'Tarzan'
Jane & 'Tarzan'
方法二 对COOKIE进行IP绑定
cookie里面一般有自动登录信息和session_id,就算对cookie里面的内容全部加了密,cookie的信息一但被别人通过XSS攻击获取后也一样等同于把自己的帐号密码给了别人。
对cookie进行IP绑定,(当然也可以获取用户客户端更多的其它信息进行同时绑定)可以根据用户的IP来判断这个cookie是不是来原始授权用户。代码案例如下
- 用户设置了自动登录时保存自动登录信息:
- $auto=I('post.auto');//用户设置了自动登录
- if(!empty($auto)){
- cookie('auto',encrypt(serialize($data)));//将登录信息保存到cookie,其中$data里含有加密后的帐号,密码,和用户的IP,这里的cookie已在全局中设置过期日期为一周
- }
- 用户关闭浏览器再次访问网站时,进行自动登录
- if (!is_login()) {//是否未登录状态?
- $auth=cookie('auto');
- if(!empty($auth)){//是否未有自动登录cookie?
- $data=unserialize(decrypt($auth));
- if(!empty($data) && !empty($data['username']) && !empty($data['password']) && !empty($data['last_login_ip'])){
- $user=M('Member')->where(array('username'=>$data['username'],'password'=>$data['password']))->find();
- if(!empty($user['id'])&&($user['last_login_ip']==get_client_ip())){//cookie帐号密码是否有效?//IP来源是否相同?
- login_session($user['id'], $user['username'], $data['last_login_ip']);//用户自动登录成功
- }
- }
- }
- }
优点:大多数场景下可使被XSS攻击盗取的cookie失效。缺点:由于IP存在多台电脑共用的可能,对绑定做不到十分精细。
方法三 HTML5值得观注的新特性:
<iframe src="http://alibaba.com" sandbox>为iframe的增加的sandbox属性,可以防止不信任的Web页面执行某些操作.相信这个方法以后会被广泛使用
方法四 这有一个remove—xss方法,可以调用
function remove_xss($val) { // remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed // this prevents some character re-spacing such as <java\0script> // note that you have to handle splits with \n, \r, and \t later since they *are* allowed in some inputs $val = preg_replace('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '', $val); // straight replacements, the user should never need these since they're normal characters // this prevents like <IMG SRC=@avascript:alert('XSS')> $search = 'abcdefghijklmnopqrstuvwxyz'; $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; $search .= '1234567890!@#$%^&*()'; $search .= '~`";:?+/={}[]-_|\'\\'; for ($i = 0; $i < strlen($search); $i++) { // ;? matches the ;, which is optional // 0{0,7} matches any padded zeros, which are optional and go up to 8 chars // @ @ search for the hex values $val = preg_replace('/(&#[xX]0{0,8}'.dechex(ord($search[$i])).';?)/i', $search[$i], $val); // with a ; // @ @ 0{0,7} matches '0' zero to seven times $val = preg_replace('/(�{0,8}'.ord($search[$i]).';?)/', $search[$i], $val); // with a ; } // now the only remaining whitespace attacks are \t, \n, and \r $ra1 = array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base'); $ra2 = array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload'); $ra = array_merge($ra1, $ra2); $found = true; // keep replacing as long as the previous round replaced something while ($found == true) { $val_before = $val; for ($i = 0; $i < sizeof($ra); $i++) { $pattern = '/'; for ($j = 0; $j < strlen($ra[$i]); $j++) { if ($j > 0) { $pattern .= '('; $pattern .= '(&#[xX]0{0,8}([9ab]);)'; $pattern .= '|'; $pattern .= '|(�{0,8}([9|10|13]);)'; $pattern .= ')*'; } $pattern .= $ra[$i][$j]; } $pattern .= '/i'; $replacement = substr($ra[$i], 0, 2).'<x>'.substr($ra[$i], 2); // add in <> to nerf the tag $val = preg_replace($pattern, $replacement, $val); // filter out the hex tags if ($val_before == $val) { // no replacements were made, so exit the loop $found = false; } } } return $val; }
以上是本人个人经验积累,具体解决办法还要根据每个人编程的情况具体分析。请多指教~