如何更改java过滤器中的请求主体以防止XSS
攻击?
我构建了HttpServletRequestWrapper
并使用getparameter
进行了更改
获得流关闭异常。
答案 0 :(得分:2)
public class XSSFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
XSSRequestWrapper wrappedRequest = new XSSRequestWrapper(
(HttpServletRequest) request);
String body = IOUtils.toString(wrappedRequest.getReader());
if(!"".equals(body))
{
JSONObject oldJsonObject = new JSONObject(body);
JSONObject newJsonObject = new JSONObject();
for(String key : oldJsonObject.keySet())
{
newJsonObject.put(key, XSSUtils.stripXSS(oldJsonObject.get(key).toString()));
}
wrappedRequest.resetInputStream(newJsonObject.toString().getBytes());
}
chain.doFilter(wrappedRequest, response);
}
}
public class XSSRequestWrapper extends HttpServletRequestWrapper {
private byte[] rawData;
private HttpServletRequest request;
private ResettableServletInputStream servletStream;
public XSSRequestWrapper(HttpServletRequest request) {
super(request);
this.request = request;
this.servletStream = new ResettableServletInputStream();
}
public void resetInputStream(byte[] newRawData) {
servletStream.stream = new ByteArrayInputStream(newRawData);
}
@Override
public ServletInputStream getInputStream() throws IOException {
if (rawData == null) {
rawData = IOUtils.toByteArray(this.request.getReader());
servletStream.stream = new ByteArrayInputStream(rawData);
}
return servletStream;
}
@Override
public BufferedReader getReader() throws IOException {
if (rawData == null) {
rawData = IOUtils.toByteArray(this.request.getReader());
servletStream.stream = new ByteArrayInputStream(rawData);
}
return new BufferedReader(new InputStreamReader(servletStream));
}
private class ResettableServletInputStream extends ServletInputStream {
private InputStream stream;
@Override
public int read() throws IOException {
return stream.read();
}
}
}
public class XSSUtils {
private XSSUtils()
{
}
public static String stripXSS(String value) {
return value == null ? value : escapeHtml4(value);
}
}
答案 1 :(得分:0)
由于我没有足够的声誉来添加评论,因此我将其添加为答案。 3年后,我找到了可接受的答案以节省我的时间。同时,我不得不修复几处问题,因此添加了...
(1)一个错误(缺少对rawData的分配)
public void resetInputStream(byte[] newRawData) {
rawData = newRawData;
servletStream.stream = new ByteArrayInputStream(newRawData);
}
(2)需要随时间进行更改。参考: https://stackoverflow.com/questions/29208456/httpservletrequestwrapper-example-implementation-for-setreadlistener-isfinish