好吧,我终于做到了,我将我的解决方案发布为响应而不是评论,它很实用,但不是很强大,如果您希望我使用异常处理程序等改进它,请告诉我
AntiXssDemoApplication.java 是
包 com.melardev.stackoverflow.demos.antixssdemo;
import com.melardev.stackoverflow.demos.antixssdemo.filters.AntiXssFilter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import javax.servlet.Filter;
@SpringBootApplication
@ServletComponentScan
public class AntiXssDemoApplication {
public static void main(String[] args) {
SpringApplication.run(AntiXssDemoApplication.class, args);
}
}
反Xss过滤器
package com.melardev.stackoverflow.demos.antixssdemo.filters;
import org.springframework.web.util.HtmlUtils;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
@WebFilter(urlPatterns = "/*")
public class AntiXssFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("Filter initialized");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
String userInput = servletRequest.getParameter("param");
if (userInput != null && !userInput.equalsIgnoreCase(HtmlUtils.htmlEscape(userInput)))
throw new RuntimeException();
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
System.out.println("destroy");
}
}
控制器
package com.melardev.stackoverflow.demos.antixssdemo.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/")
public class HomeController {
@RequestMapping("/xss-reflected")
@ResponseBody
public String xssDemo(@RequestParam("param") String userInput) {
return userInput;
}
}
演示:
- 打开浏览器 localhost:8080/xss-reflected?param=看看这个反射的内容,有效!
- 打开浏览器 localhost:8080/xss-reflected?param=
看看这个反射的内容,有效!!
在步骤 2 中,我使用了 html 标签 h2。您应该看到 Filter 抛出运行时异常,发生的情况是:
Filter 会拦截所有 url(因为 urlPatterns=/**),每次拦截都会调用 doFilter,如果用户提供了 Html 内容,那么 HtmlUtils.htmlEscape 会返回过滤后的字符串,换句话说,返回的字符串与原始的,这意味着用户在他的 json 输入中提供了 Html,这不是我们所期望的,所以我们抛出异常,
如果返回的字符串与 htmlEscape(userInput) 返回的字符串相同,这意味着用户没有提供任何 Html 内容,在这种情况下,我们让请求管道像往常一样流动,使用 filterChain.doFilter(servletRequest, servletResponse);
我没有使用实时 XSS 演示,因为 chrome 很可能会保护您,因为它是任何人都检测到的非常基本的反射 XSS ...
Spring Boot骨架项目下载自https://start.spring.io/ https://start.spring.io/将 Web 作为唯一的启动依赖项。
编辑:改进的代码