PHP防SQL注入和XSS攻击

摘要: 就是通过把SQL命令插入到Web表单提交或输入域名或页面请求的查询字符串,最终达到欺骗服务器执行恶意的SQL命令.在用户名输入框中输入:' or 1=1#,密码随便输入,这时候的合成后的SQL查询语句为“#”在mysql中是注释符,这样井号后面的内容将被mysql视为注释内容,这样就不会去执行了,...

就是通过把SQL命令插入到Web表单提交或输入域名或页面请求的查询字符串,最终达到欺骗服务器执行恶意的SQL命令.在用户名输入框中输入:' or 1=1#,密码随便输入,这时候的合成后的SQL查询语句为“#”在mysql中是注释符,这样井号后面的内容将被mysql视为注释内容,这样就不会去执行了,等价于
 
1 select * from users where username='' or 1=1   
防止SQL注入
 1 <?php  
 2 $field = explode(',', $data);  
 3 array_walk($field, array($this, 'add_special_char'));  
 4 $data = implode(',', $field);  
 5 /** 
 6  * 对字段两边加反引号,以保证数据库安全 
 7  * @param $value 数组值 
 8  */  
 9 function add_special_char(&$value)  
10 {  
11     if ('*' == $value || false !== strpos($value, '(') || false !== strpos($value, '.') || false !== strpos($value, '`')) {  
12         //不处理包含* 或者 使用了sql方法。  
13     } else {  
14         $value = '`' . trim($value) . '`';  
15     }  
16     return $value;  
17 }  
18   
19 /* 
20 函数名称:inject_check() 
21 函数作用:检测提交的值是不是含有SQL注入的字符,保护服务器安全 
22 参  数:$sql_str: 提交的变量inject_check($id) { exit('提交的参数非法!'); 
23 返 回 值:返回检测结果,true or false 
24 */  
25 function inject_check($sql_str)  
26 {  
27     return preg_match('/^select|insert|and|or|create|update|delete|alter|count|\'|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile/i', $sql_str); // 进行过滤  
28 }  
29   
30 //递归ddslashes  
31 function daddslashes($string, $force = 0, $strip = FALSE)  
32 {  
33     if (!get_magic_quotes_gpc() || $force) {  
34         if (is_array($string)) {  
35             foreach ($string as $key => $val) {  
36                 $string [$key] = daddslashes($val, $force);  
37             }  
38         } else {  
39             $string = addslashes($strip ? stripslashes($string) : $string);  
40         }  
41     }  
42     return $string;  
43 }  
44   
45 //递归stripslashes  
46 function dstripslashes($string)  
47 {  
48     if (is_array($string)) {  
49         foreach ($string as $key => $val) {  
50             $string [$key] = $this->dstripslashes($val);  
51         }  
52     } else {  
53         $string = stripslashes($string);  
54     }  
55     return $string;  
56 }  

 

CSRF攻击(跨站请求伪造)原理比较简单,如图1所示。
其中Web A为存在CSRF漏洞的网站,Web B为攻击者构建的恶意网站,User C为Web A网站的合法用户。

1. 用户C打开浏览器,访问受信任网站A,输入用户名和密码请求登录网站A;
2.在用户信息通过验证后,网站A产生Cookie信息并返回给浏览器,此时用户登录网站A成功,可以正常发送请求到网站A;
3. 用户未退出网站A之前,在同一浏览器中,打开一个TAB页访问网站B;
4. 网站B接收到用户请求后,返回一些攻击性代码,并发出一个请求要求访问第三方站点A;
5. 浏览器在接收到这些攻击性代码后,根据网站B的请求,在用户不知情的情况下携带Cookie信息,向网站A发出请求。网站A并不知道该请求其实是由B发起的,所以会根据用户C的Cookie信息以C的权限处理该请求,导致来自网站B的恶意代码被执行。

网站A

  1. <?php  
  2. session_start();  
  3. if (isset($_POST['toBankId']) && isset($_POST['money'])) {  
  4.     buy_stocks($_POST['toBankId'], $_POST['money']);  
  5. }  
  6. ?>  

危险网站B

 1 <html>  
 2 <head>  
 3     <script type="text/javascript">  
 4         function steal() {  
 5             iframe = document.frames["steal"];  
 6             iframe.document.Submit("transfer");  
 7         }  
 8     </script>  
 9 </head>  
10     
11 <body onload="steal()">  
12 <iframe name="steal" display="none">  
13     <form method="POST" name="transfer" action="http://www.myBank.com/Transfer.php">  
14      <input type="hidden" name="toBankId" value="11">  
15      <input type="hidden" name="money" value="1000">  
16    </form>  
17 </iframe>  
18 </body>  
19 </html>  

 

修复方式:1验证码 2检测refer 3目前主流的做法是使用Token抵御CSRF攻击 

 

XSS(跨站脚本)它允许恶意web用户将代码植入到提供给其它用户使用的页面中。比如这些代码包括HTML代码和客户端脚本.

当用户点击以上攻击者提供的URL时,index.php页面被植入脚本,页面源码如下:

1 <?php  
2 $name = $_GET['name'];  
3 echo "Welcome $name<br>";  
4 echo '<a href="http://www.cnblogs.com/bangerlee/">Click to Download</a>';  
5 ?>  

这时,当攻击者给出以下URL链接:

1 index.php?name=guest<script>alert('attacked')</script>   

当用户点击该链接时,将产生以下html代码,带'attacked'的告警提示框弹出:

1 Welcome guest  
2 <script>alert('attacked')</script>  
3 <br>  
4 <a href='http://www.cnblogs.com/bangerlee/'>Click to Download</a>  

跨站脚本的过滤RemoveXss函数

 1 function RemoveXSS($val) {  
 2    // remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed  
 3    // this prevents some character re-spacing such as <java\0script>  
 4    // note that you have to handle splits with \n, \r, and \t later since they *are* allowed in some inputs  
 5    $val = preg_replace('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '', $val);  
 6    // straight replacements, the user should never need these since they're normal characters  
 7    // this prevents like <IMG SRC=@avascript:alert('XSS')>  
 8    $search = 'abcdefghijklmnopqrstuvwxyz';  
 9    $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';  
10    $search .= '1234567890!@#$%^&*()';  
11    $search .= '~`";:?+/={}[]-_|\'\\';  
12    for ($i = 0; $i < strlen($search); $i++) {  
13       // ;? matches the ;, which is optional  
14       // 0{0,7} matches any padded zeros, which are optional and go up to 8 chars  
15   
16       // @ @ search for the hex values  
17       $val = preg_replace('/(&#[xX]0{0,8}'.dechex(ord($search[$i])).';?)/i', $search[$i], $val); // with a ;  
18       // @ @ 0{0,7} matches '0' zero to seven times  
19       $val = preg_replace('/(&#0{0,8}'.ord($search[$i]).';?)/', $search[$i], $val); // with a ;  
20    }  
21   
22    // now the only remaining whitespace attacks are \t, \n, and \r  
23    $ra1 = array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');  
24    $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');  
25    $ra = array_merge($ra1, $ra2);  
26   
27    $found = true; // keep replacing as long as the previous round replaced something  
28    while ($found == true) {  
29       $val_before = $val;  
30       for ($i = 0; $i < sizeof($ra); $i++) {  
31          $pattern = '/';  
32          for ($j = 0; $j < strlen($ra[$i]); $j++) {  
33             if ($j > 0) {  
34                $pattern .= '(';  
35                $pattern .= '(&#[xX]0{0,8}([9ab]);)';  
36                $pattern .= '|';  
37                $pattern .= '|(&#0{0,8}([9|10|13]);)';  
38                $pattern .= ')*';  
39             }  
40             $pattern .= $ra[$i][$j];  
41          }  
42          $pattern .= '/i';  
43          $replacement = substr($ra[$i], 0, 2).'<x>'.substr($ra[$i], 2); // add in <> to nerf the tag  
44          $val = preg_replace($pattern, $replacement, $val); // filter out the hex tags  
45          if ($val_before == $val) {  
46             // no replacements were made, so exit the loop  
47             $found = false;  
48          }  
49       }  
50    }  
51    return $val;  
52 }  

 

posted @ 2018-08-10 16:19  liluxiang  阅读(12067)  评论(1编辑  收藏  举报