防止HttpServlet请求.getHeader()的跨站点脚本(XSS)攻击



我们使用的是java和spring-boot。我想从HttpServletRequest中读取一些标头值。

String header = request.getHeader("SomeHeader");

但我们的代码质量工具是这样抱怨的:

The application's testMethod embeds untrusted data in the generated output with SomeHeader, at line 265 of srcmainjavacomtestpoccontrollerTest.java. This untrusted data is embedded straight into the output without proper sanitization or encoding, enabling an attacker to inject malicious code into the output.
The attacker would be able to alter the returned web page by simply providing modified data in the user input getHeader, which is read by the getCorrelationId method at line 265 of srcmainjavacomtestpoccontrollerTest.java. This input then flows through the code straight to the output web page, without sanitization. 
This can enable a Reflected Cross-Site Scripting (XSS) attack.

我已经在谷歌上搜索并尝试了以下使用owasp编码器依赖项的代码,但仍然存在同样的问题。

String header = Encode.forJava(request.getHeader("SomeHeader"));

我的方法如下:

private String testMethod(HttpServletRequest request) {
String header = Encode.forJava(request.getHeader("SomeHeader"));
return header;
}

我会在另一个方法中调用上面的方法,并想验证它是否为null或不是

private void anotherMethod() {
String header = testMethod();
if (header != null) {
//do something
} else {
//do something
}
}

有人能指导如何解决这个问题吗?

编码是在输出而非输入上完成的,因此应该在输出值时完成。

要使用的编码器取决于输出格式。如果您正在生成HTML,那么您可以使用Encode.forHtml

最新更新