標籤:第三方 alt replace tco 輸出 瀏覽器 偽造 security for
最近測試XSS攻擊修複時,找到的一個比較不錯的文章,分享給大家。
Update20151202:
感謝大家的關注和回答,目前我從各種方式瞭解到的防禦方法,整理如下:
PHP直接輸出html的,可以採用以下的方法進行過濾:
5 |
3.HTMLPurifier.auto.php外掛程式 |
PHP輸出到JS代碼中,或者開發Json API的,則需要前端在JS中進行過濾:
1 |
1.盡量使用innerText(IE)和textContent(Firefox),也就是jQuery的text()來輸出常值內容 |
3 |
2.必須要用innerHTML等等函數,則需要做類似php的htmlspecialchars的過濾(參照@eechen的答案) |
其它的通用的補充性防禦手段
01 |
1.在輸出html時,加上Content Security Policy的Http Header |
03 |
(作用:可以防止頁面被XSS攻擊時,嵌入第三方的指令檔等) |
06 |
2.在設定Cookie時,加上HttpOnly參數 |
08 |
(作用:可以防止頁面被XSS攻擊時,Cookie資訊被盜取,可相容至IE6) |
09 |
(缺陷:網站本身的JS代碼也無法操作Cookie,而且作用有限,只能保證Cookie的安全) |
11 |
3.在開發API時,檢驗請求的Referer參數 |
14 |
(缺陷:IE或低版本的瀏覽器中,Referer參數可以被偽造) |
4、補充一個xss過濾的函數。。
01 |
function clean_xss(&$string, $low = False) |
03 |
if (! is_array ( $string )) |
05 |
$string = trim ( $string ); |
06 |
$string = strip_tags ( $string ); |
07 |
$string = htmlspecialchars ( $string ); |
12 |
$string = str_replace ( array (‘"‘, "\\", "‘", "/", "..", "../", "./", "//" ), ‘‘, $string ); |
13 |
$no = ‘/%0[0-8bcef]/‘; |
14 |
$string = preg_replace ( $no, ‘‘, $string ); |
16 |
$string = preg_replace ( $no, ‘‘, $string ); |
17 |
$no = ‘/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/S‘; |
18 |
$string = preg_replace ( $no, ‘‘, $string ); |
21 |
$keys = array_keys ( $string ); |
22 |
foreach ( $keys as $key ) |
24 |
clean_xss ( $string [$key] ); |
PHP防禦XSS攻擊的終極解決方案