PHP防禦XSS攻擊的終極解決方案

來源:互聯網
上載者:User

標籤:第三方   alt   replace   tco   輸出   瀏覽器   偽造   security   for   

最近測試XSS攻擊修複時,找到的一個比較不錯的文章,分享給大家。

Update20151202:

感謝大家的關注和回答,目前我從各種方式瞭解到的防禦方法,整理如下:

PHP直接輸出html的,可以採用以下的方法進行過濾:

1 1.htmlspecialchars函數
2  
3 2.htmlentities函數
4  
5 3.HTMLPurifier.auto.php外掛程式
6  
7 4.RemoveXss函數(百度可以查到)

PHP輸出到JS代碼中,或者開發Json API的,則需要前端在JS中進行過濾:

1 1.盡量使用innerText(IE)和textContent(Firefox),也就是jQuery的text()來輸出常值內容
2  
3 2.必須要用innerHTML等等函數,則需要做類似php的htmlspecialchars的過濾(參照@eechen的答案)

其它的通用的補充性防禦手段

01 1.在輸出html時,加上Content Security Policy的Http Header
02  
03 (作用:可以防止頁面被XSS攻擊時,嵌入第三方的指令檔等)
04 (缺陷:IE或低版本的瀏覽器可能不支援)
05  
06 2.在設定Cookie時,加上HttpOnly參數
07  
08 (作用:可以防止頁面被XSS攻擊時,Cookie資訊被盜取,可相容至IE6)
09 (缺陷:網站本身的JS代碼也無法操作Cookie,而且作用有限,只能保證Cookie的安全)
10  
11 3.在開發API時,檢驗請求的Referer參數
12  
13 (作用:可以在一定程度上防止CSRF攻擊)
14 (缺陷:IE或低版本的瀏覽器中,Referer參數可以被偽造)

4、補充一個xss過濾的函數。。

01 function clean_xss(&$string$low = False)
02     {
03         if (! is_array $string ))
04         {
05             $string = trim ( $string );
06             $string strip_tags $string );
07             $string = htmlspecialchars ( $string );
08             if ($low)
09             {
10                 return True;
11             }
12             $string str_replace array (‘"‘, "\\", "‘", "/", "..", "../", "./", "//" ), ‘‘, $string );
13             $no ‘/%0[0-8bcef]/‘;
14             $string = preg_replace ( $no‘‘$string );
15             $no ‘/%1[0-9a-f]/‘;
16             $string = preg_replace ( $no‘‘$string );
17             $no ‘/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/S‘;
18             $string = preg_replace ( $no‘‘$string );
19             return True;
20         }
21         $keys array_keys $string );
22         foreach $keys as $key )
23         {
24             clean_xss ( $string [$key] );
25         }
26     }

PHP防禦XSS攻擊的終極解決方案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.