深入了解Java中的XSS攻击
存在XSS漏洞的java代码:
第一段
反射型XSS
@RequestMapping("/reflect")
@ResponseBody
public static String reflect(String xss) {
return xss;
}
payload
http://localhost:8888/xss/reflect?xss=%3Cscript%3Ealert(%27tpa%27);%3C/script%3E
第二段
存储型XSS
@RequestMapping("/stored/store")
@ResponseBody
public String store(String xss, HttpServletResponse response) {
Cookie cookie = new Cookie("xss", xss);
response.addCookie(cookie);
return "Set param into cookie";
}
访问如下地址存储脚本到Cookie中
http://localhost:8888/xss/stored/store?xss=%3Cscript%3Ealert(%27tpa%27)%3C/script%3E
当后端再获取Cookie返回时
@RequestMapping("/stored/show")
@ResponseBody
public String show(@CookieValue("xss") String xss) {
return xss;
}
访问
http://localhost:8888/xss/stored/show
成功弹窗
修复
目前最有效的办法,对特殊字符进行实体转义。
XSS安全代码:
@RequestMapping("/safe")
@ResponseBody
public static String safe(String xss) {
return encode(xss);
}
private static String encode(String origin) {
origin = StringUtils.replace(origin, "&", "&");
origin = StringUtils.replace(origin, "<", "<");
origin = StringUtils.replace(origin, ">", ">");
origin = StringUtils.replace(origin, "\"", """);
origin = StringUtils.replace(origin, "'", "'");
origin = StringUtils.replace(origin, "/", "/");
return origin;
}
XSS排查
利用xsstriker等工具进行扫描
手动输入特殊字符看被没被实体转义
关键字:getParamter、<%=、param