天天看點

XSS學習筆記(五)-XSS防禦

隻要是産生XSS的地方都是伴随着輸入或者輸出的,是以抓住問題的主要沖突,問題也就有了解決的方法了:可以在輸入端嚴格過濾,也可以在輸出時候過濾,就是在從使用者輸入的或輸出到使用者的GET或POST中是否有敏感字元:

輸入過濾:

過濾 ' " , <  > \   <!--

用戶端: 開啟 XSS filter 

輸出過濾(轉義):

轉義: ' "  \ <  <!-- (轉義為&#32; 等HTML寫死)

過濾: <script> href </script>模型 , window.location 模型 等

浏覽器防禦:IE 8 以上的核心 開啟 XSS filter ,chrome ctrl+ shift + N  開啟隐身浏覽 , firefox Noscript 插件

其實有很多測試XSS攻擊的工具:

Paros proxy (http://www.parosproxy.org)

Fiddler (http://www.fiddlertool.com/fiddler) (點選Toolbar上的"TextWizard" 按鈕)

Burp proxy (http://www.portswigger.net/proxy/)

TamperIE (http://www.bayden.com/dl/TamperIESetup.exe)

下面貼一個 常見的php過濾XSS的函數:

<?PHP
/**
 * @blog http://www.phpddt.com
 * @param $string
 * @param $low 安全别級低
 */
function clean_xss(&$string, $low = False)
{
    if (! is_array ( $string ))
    {
        $string = trim ( $string );
        $string = strip_tags ( $string );
        $string = htmlspecialchars ( $string );
        if ($low)
        {
            return True;
        }
        $string = str_replace ( array ('"', "\\", "'", "/", "..", "../", "./", "//" ), '', $string );
        $no = '/%0[0-8bcef]/';
        $string = preg_replace ( $no, '', $string );
        $no = '/%1[0-9a-f]/';
        $string = preg_replace ( $no, '', $string );
        $no = '/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/S';
        $string = preg_replace ( $no, '', $string );
        return True;
    }
    $keys = array_keys ( $string );
    foreach ( $keys as $key )
    {
        clean_xss ( $string [$key] );
    }
}
//just a test
$str = 'phpddt.com<meta http-equiv="refresh" content="0;">';
clean_xss($str); //如果你把這個注釋掉,你就知道xss攻擊的厲害了
echo $str;
?>
           

通過clean_xss()就過濾了惡意内容!