当前位置:首页 > PHP教程 > php高级应用 > 列表

谈谈​PHP防止XSS跨站脚本攻击的方法

发布:smiling 来源: PHP粉丝网  添加日期:2022-07-11 11:37:52 浏览: 评论:0 

PHP防止XSS跨站脚本攻击的方法:是针对非法的HTML代码包括单双引号等,使用htmlspecialchars()函数 。

在使用htmlspecialchars()函数的时候注意第二个参数, 直接用htmlspecialchars($string) 的话,第二个参数默认是ENT_COMPAT,函数默认只是转化双引号(“), 不对单引号(‘)做转义.

所以,htmlspecialchars函数更多的时候要加上第二个参数, 应该这样用: htmlspecialchars($string,ENT_QUOTES).当然,如果需要不转化任何引号,用htmlspecialchars($string,ENT_NOQUOTES).

另外, 尽量少用htmlentities, 在全部英文的时候htmlentities和htmlspecialchars没有区别,都可以达到目的.但是,中文情况下, htmlentities却会转化所有的html代码,连同里面的它无法识别的中文字符也给转化了。

htmlentities和htmlspecialchars这两个函数对 '之类的字符串支持不好,都不能转化, 所以用htmlentities和htmlspecialchars转化的字符串只能防止XSS攻击,不能防止SQL注入攻击.

所有有打印的语句如echo,print等 在打印前都要使用htmlentities() 进行过滤,这样可以防止Xss,注意中文要写出htmlentities($name,ENT_NOQUOTES,GB2312) 。

(1).网页不停地刷新 '<meta http-equiv="refresh" content="0;">'

(2).嵌入其它网站的链接 <iframe src=http://xxxx width=250 height=250></iframe> 除了通过正常途径输入XSS攻击字符外,还可以绕过JavaScript校验,通过修改请求达到XSS攻击的目的.

  1. <?php 
  2.  
  3. //php防注入和XSS攻击通用过滤 
  4.  
  5. $_GET     && SafeFilter($_GET); 
  6.  
  7. $_POST    && SafeFilter($_POST); 
  8.  
  9. $_COOKIE  && SafeFilter($_COOKIE); 
  10.  
  11.     
  12.  
  13. function SafeFilter (&$arr)  
  14.  
  15. { 
  16.  
  17.    $ra=Array('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/','/script/','/javascript/','/vbscript/','/expression/','/applet/' 
  18.  
  19.    ,'/meta/','/xml/','/blink/','/link/','/style/','/embed/','/object/','/frame/','/layer/','/title/','/bgsound/' 
  20.  
  21.    ,'/base/','/onload/','/onunload/','/onchange/','/onsubmit/','/onreset/','/onselect/','/onblur/','/onfocus/', 
  22.  
  23.    '/onabort/','/onkeydown/','/onkeypress/','/onkeyup/','/onclick/','/ondblclick/','/onmousedown/','/onmousemove/' 
  24.  
  25.    ,'/onmouseout/','/onmouseover/','/onmouseup/','/onunload/'); 
  26.  
  27.        
  28.  
  29.    if (is_array($arr)) 
  30.  
  31.    { 
  32.  
  33.      foreach ($arr as $key => $value)  
  34.  
  35.      { 
  36.  
  37.         if (!is_array($value)) 
  38.  
  39.         { 
  40.  
  41.           if (!get_magic_quotes_gpc())  //不对magic_quotes_gpc转义过的字符使用addslashes(),避免双重转义。 
  42.  
  43.           { 
  44.  
  45.              $value  = addslashes($value); //给单引号(')、双引号(")、反斜线(\)与 NUL(NULL 字符) 
  46.  
  47.              #加上反斜线转义 
  48.  
  49.           } 
  50.  
  51.           $value       = preg_replace($ra,'',$value);     //删除非打印字符,粗暴式过滤xss可疑字符串 
  52.  
  53.           $arr[$key]     = htmlentities(strip_tags($value)); //去除 HTML 和 PHP 标记并转换为 HTML 实体 
  54.  
  55.         } 
  56.  
  57.         else 
  58.  
  59.         { 
  60.  
  61.           SafeFilter($arr[$key]); 
  62.  
  63.         } 
  64.  
  65.      } 
  66.  
  67.    } 
  68.  
  69. } 
  70.  
  71. ?> 
  72.  
  73. $str = 'www.phpfensi.com<meta http-equiv="refresh" content="0;">'; 
  74.  
  75. SafeFilter ($str); //如果你把这个注释掉,提交之后就会无休止刷新 
  76.  
  77. echo $str; 
  78.  
  79. //------------------------------php防注入和XSS攻击通用过滤-----Start--------------------------------------------// 
  80.  
  81. function string_remove_xss($html) { 
  82.  
  83.     preg_match_all("/\<([^\<]+)\>/is", $html, $ms); 
  84.  
  85.    
  86.  
  87.     $searchs[] = '<'; 
  88.  
  89.     $replaces[] = '<'; 
  90.  
  91.     $searchs[] = '>'; 
  92.  
  93.     $replaces[] = '>'; 
  94.  
  95.    
  96.  
  97.     if ($ms[1]) { 
  98.  
  99.         $allowtags = 'img|a|font|div|table|tbody|caption|tr|td|th|br|p|b|strong|i|u|em|span|ol|ul|li|blockquote'; 
  100.  
  101.         $ms[1] = array_unique($ms[1]); 
  102.  
  103.         foreach ($ms[1] as $value) { 
  104.  
  105.             $searchs[] = "<".$value.">"; 
  106.  
  107.    
  108.  
  109.             $value = str_replace('&', '_uch_tmp_str_', $value); 
  110.  
  111.             $value = string_htmlspecialchars($value); 
  112.  
  113.             $value = str_replace('_uch_tmp_str_', '&', $value); 
  114.  
  115.    
  116.  
  117.             $value = str_replace(array('\\', '/*'), array('.', '/.'), $value); 
  118.  
  119.             $skipkeys = array('onabort','onactivate','onafterprint','onafterupdate','onbeforeactivate','onbeforecopy','onbeforecut','onbeforedeactivate', 
  120.  
  121.                     'onbeforeeditfocus','onbeforepaste','onbeforeprint','onbeforeunload','onbeforeupdate','onblur','onbounce','oncellchange','onchange', 
  122.  
  123.                     'onclick','oncontextmenu','oncontrolselect','oncopy','oncut','ondataavailable','ondatasetchanged','ondatasetcomplete','ondblclick', 
  124.  
  125.                     'ondeactivate','ondrag','ondragend','ondragenter','ondragleave','ondragover','ondragstart','ondrop','onerror','onerrorupdate', 
  126.  
  127.                     'onfilterchange','onfinish','onfocus','onfocusin','onfocusout','onhelp','onkeydown','onkeypress','onkeyup','onlayoutcomplete', 
  128.  
  129.                     'onload','onlosecapture','onmousedown','onmouseenter','onmouseleave','onmousemove','onmouseout','onmouseover','onmouseup','onmousewheel', 
  130.  
  131.                     'onmove','onmoveend','onmovestart','onpaste','onpropertychange','onreadystatechange','onreset','onresize','onresizeend','onresizestart', 
  132.  
  133.                     'onrowenter','onrowexit','onrowsdelete','onrowsinserted','onscroll','onselect','onselectionchange','onselectstart','onstart','onstop', 
  134.  
  135.                     'onsubmit','onunload','javascript','script','eval','behaviour','expression','style','class'); 
  136.  
  137.             $skipstr = implode('|', $skipkeys); 
  138.  
  139.             $value = preg_replace(array("/($skipstr)/i"), '.', $value); 
  140.  
  141.             if (!preg_match("/^[\/|\s]?($allowtags)(\s+|$)/is", $value)) { 
  142.  
  143.                 $value = ''; 
  144.  
  145.             } 
  146.  
  147.             $replaces[] = emptyempty($value) ? '' : "<" . str_replace('"', '"', $value) . ">"; 
  148.  
  149.         } 
  150.  
  151.     } 
  152.  
  153.     $html = str_replace($searchs, $replaces, $html); 
  154.  
  155.    
  156.  
  157.     return $html; 
  158.  
  159. } 
  160.  
  161. //php防注入和XSS攻击通用过滤  
  162.  
  163. function string_htmlspecialchars($string, $flags = null) { 
  164.  
  165.     if (is_array($string)) { 
  166.  
  167.         foreach ($string as $key => $val) { 
  168.  
  169.             $string[$key] = string_htmlspecialchars($val, $flags); 
  170.  
  171.         } 
  172.  
  173.     } else { 
  174.  
  175.         if ($flags === null) { 
  176.  
  177.             $string = str_replace(array('&', '"', '<', '>'), array('&', '"', '<', '>'), $string); 
  178.  
  179.             if (strpos($string, '&#') !== false) { 
  180.  
  181.                 $string = preg_replace('/&((#(\d{3,5}|x[a-fA-F0-9]{4}));)/', '&\\1', $string); 
  182.  
  183.             } 
  184.  
  185.         } else { 
  186.  
  187.             if (PHP_VERSION < '5.4.0') { 
  188.  
  189.                 $string = htmlspecialchars($string, $flags); 
  190.  
  191.             } else { 
  192.  
  193.                 if (!defined('CHARSET') || (strtolower(CHARSET) == 'utf-8')) { 
  194.  
  195.                     $charset = 'UTF-8'; 
  196.  
  197.                 } else { 
  198.  
  199.                     $charset = 'ISO-8859-1'; 
  200.  
  201.                 } 
  202.  
  203.                 $string = htmlspecialchars($string, $flags, $charset); 
  204.  
  205.             } 
  206.  
  207.         } 
  208.  
  209.     } 
  210.  
  211.    
  212.  
  213.     return $string; 
  214.  
  215. } 
  216.  
  217.  
  218.  
  219. //------------------php防注入和XSS攻击通用过滤-----End--------------------------------------------// 

PHP中的设置

PHP5.2以上版本已支持HttpOnly参数的设置,同样也支持全局的HttpOnly的设置,在php.ini中

-----------------------------------------------------

session.cookie_httponly =

-----------------------------------------------------

设置其值为1或者TRUE,来开启全局的Cookie的HttpOnly属性,当然也支持在代码中来开启:

  1. <?php ini_set("session.cookie_httponly", 1);    
  2.  
  3. // or session_set_cookie_params(0, NULL, NULL, NULL, TRUE);    
  4.  
  5. ?> 

Cookie操作函数setcookie函数和setrawcookie函数也专门添加了第7个参数来做为HttpOnly的选项,开启方法为:

  1. <?php   
  2.  
  3. setcookie("abc", "test", NULL, NULL, NULL, NULL, TRUE);    
  4.  
  5. setrawcookie("abc", "test", NULL, NULL, NULL, NULL, TRUE);   
  6.  
  7. ?>

Tags: PHP跨站脚本攻击 XSS

分享到: