xss跨站脚本攻击(XSS),是最普遍的Web应用安全漏洞。这类漏洞能够使得攻击者嵌入恶意脚本代码到正常用户会访问到的页面中,当正常用户访问该页面时,则可导致嵌入的恶意脚本代码的执行,从而达到恶意攻击用户的目的。下面给大家介绍一款防XSS的类库,Github地址:https://github.com/voku/anti-xss
一、安装
composer require voku/anti-xss
二、使用
use voku\helper\AntiXSS;
require_once __DIR__ . '/vendor/autoload.php';
$antiXss = new AntiXSS();
三、案例
1.处理HTML字符
$harm_string = "Hello, i try to <script>alert('Hack');</script> your site";
$harmless_string = $antiXss->xss_clean($harm_string);
// Hello, i try to alert('Hack'); your site
2.处理十六进制html字符
$harm_string = "<IMG SRC=javascript:alert('XSS')>";
$harmless_string = $antiXss->xss_clean($harm_string);
// <IMG >
3.处理Unicode十六进制字符
$harm_string = "<a href=' javascript:alert(1)'>CLICK</a>";
$harmless_string = $antiXss->xss_clean($harm_string);
// <a >CLICK</a>
4.处理Unicode字符
$harm_string = "<a href=\"\u0001java\u0003script:alert(1)\">CLICK<a>";
$harmless_string = $antiXss->xss_clean($harm_string);
// <a >CLICK</a>
5.去除内联CSS
$harm_string = '<li style="list-style-image: url(javascript:alert(0))">';
$harmless_string = $antiXss->xss_clean($harm_string);
// <li >
6.保留内联CSS
$harm_string = '<li style="list-style-image: url(javascript:alert(0))">';
$antiXss->removeEvilAttributes(array('style')); // allow style-attributes
$harmless_string = $antiXss->xss_clean($harm_string);
// <li style="list-style-image: url(alert(0))">
7.检查字符串是否包含XSS攻击
$harm_string = "\x3cscript src=http://www.example.com/malicious-code.js\x3e\x3c/script\x3e";
$harmless_string = $antiXss->xss_clean($harm_string);
$antiXss->isXssFound();
// true
8.处理iframe
$harm_string = '<iframe width="560" onclick="alert(\'xss\')" height="315" src="https://www.youtube.com/embed/foobar?rel=0&controls=0&showinfo=0" frameborder="0" allowfullscreen></iframe>';
$antiXss->removeEvilHtmlTags(array('iframe'));
$harmless_string = $antiXss->xss_clean($harm_string);
// <iframe width="560" height="315" src="https://www.youtube.com/embed/foobar?rel=0&controls=0&showinfo=0" frameborder="0" allowfullscreen></iframe>
四、备注
1.更多使用方法请参考:https://github.com/voku/anti-xss
网友评论