XSS攻击及防范

1、什么是XSS攻击

跨站脚本攻击(Cross Site Scripting),攻击者往Web页面里插入恶意Script代码,当用户浏览该页之时,嵌入其中Web里面的Script代码会被执行,从而达到恶意攻击用户的目的。

2、转化的思想防范xss攻击

转化的思想:将输入内容中的<>转化为html实体字符。

原生php中对xss攻击进行防范,使用htmlspecialchars函数,将用户输入的字符串中的特殊字符,比如<> 转化为html实体字符。

TP框架中,可以设置在获取输入变量时,使用htmlspecialchars函数对输入进行处理。

设置方法:修改application/config.php

注意:在框架配置文件中,配置的函数名称,如果写错,页面不会报错,只是所有接收的数据都是null.

'default_filter' => 'htmlspecialchars',

3、过滤的思想防范xss攻击

过滤的思想:将输入内容中的script标签js代码过滤掉。

特别在富文本编辑器中,输入的内容源代码中,包含html标签是正常的。不能使用htmlspecialchars进行处理。如果用户直接在源代码界面输入js代码,也会引起xss攻击。

通常使用htmlpurifier插件进行过滤。

使用步骤:

①使用composer执行命令,安装 ezyang/htmlpurifier 扩展类库

项目目录下> composer require ezyang/htmlpurifier

或者手动下载插件包,

将htmlpurifier插件包解压,将其中的library目录移动到项目中public/plugins目录,改名为htmlpurifier

 

②在application/common.php中定义remove_xss函数

if (!function_exists('remove_xss')) {
    //使用htmlpurifier防范xss攻击
    function remove_xss($string){
        //相对index.php入口文件,引入HTMLPurifier.auto.php核心文件
        //require_once './plugins/htmlpurifier/HTMLPurifier.auto.php';
        // 生成配置对象
        $cfg = HTMLPurifier_Config::createDefault();
        // 以下就是配置:
        $cfg -> set('Core.Encoding', 'UTF-8');
        // 设置允许使用的HTML标签
        $cfg -> set('HTML.Allowed','div,b,strong,i,em,a[href|title],ul,ol,li,br,p[style],span[style],img[width|height|alt|src]');
        // 设置允许出现的CSS样式属性
        $cfg -> set('CSS.AllowedProperties', 'font,font-size,font-weight,font-style,font-family,text-decoration,padding-left,color,background-color,text-align');
        // 设置a标签上是否允许使用target="_blank"
        $cfg -> set('HTML.TargetBlank', TRUE);
        // 使用配置生成过滤用的对象
        $obj = new HTMLPurifier($cfg);
        // 过滤字符串
        return $obj -> purify($string);
    }
} 

说明:htmlpurifier插件,会过滤掉script标签以及标签包含的js代码。

设置全局过滤方法为封装的remove_xss函数:

修改application/config.php

'default_filter' => 'remove_xss',

4、转化与过滤结合防范xss攻击

普通输入内容,使用转化的思想进行处理。

设置全局过滤方法为封装的htmlspecialchars函数:

修改application/config.php

'default_filter' => 'htmlspecialchars',

富文本编辑器内容,使用过滤的思想进行处理。

比如商品描述字段,处理如下:

//商品添加或修改功能中
$params = input();
//单独处理商品描述字段 goods_introduce
$params['goods_desc'] = input('goods_desc', '', 'remove_xss');
原文地址:https://www.cnblogs.com/ruoruchujian/p/11303873.html