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 }  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM