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',
普通輸入內容,使用轉化的思想進行處理。
設置全局過濾方法為封裝的htmlspecialchars函數:
修改application/config.php
'default_filter' => 'htmlspecialchars',
富文本編輯器內容,使用過濾的思想進行處理。
比如商品描述字段,處理如下:
//商品添加或修改功能中 $params = input(); //單獨處理商品描述字段 goods_introduce $params['goods_desc'] = input('goods_desc', '', 'remove_xss');