zl程序教程

您现在的位置是:首页 >  工具

当前栏目

XSS学习笔记(五)-XSS防御

笔记学习 XSS 防御
2023-09-27 14:23:30 时间
仅仅要是产生XSS的地方都是伴随着输入或者输出的,所以抓住问题的主要矛盾,问题也就有了解决办法了:能够在输入端严格过滤,也能够在输出时候过滤。就是在从用户输入的或输出到用户的GET或POST中是否有敏感字符:

输入过滤:
过滤 ' " , <  > \   <!--
client: 开启 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" button)
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()就过滤了恶意内容!