I am working on a Spring Boot REST application. I have to authenticate all the incoming requests. If the user is authorized then the normal flow executes if not, the user will get a 401 HTTP status with a custom response JSON.
I am doing that using the Servlet Filter
public class SecurityFilter implements Filter {
@Autowired
ObjectMapper objectMapper;
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
String apikey = httpServletRequest.getHeader(“apikey”);
if(validApikey)
{
chain.doFilter(ServletRequest, servletResponse);
}
else {
ErrorResponse errorResponse = new ErrorResponse();
errorResponse.setStatus(false);
errorResponse.setReason(“provided apikey on header is unauthorized”);
String errorMessage = objectMapper.writeValueAsString(errorResponse);
HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
httpServletResponse.setContentType(“application/json”);
httpServletResponse.setStatus(401);
httpServletResponse.getWriter().write(responseJson);
httpServletResponse.getWriter().flush();
}
Everything is working as expected. But when I try to deploy the code Fortify scan is complaining about the line
httpServletResponse.getWriter().write(responseJson);
Fortify message
The SecurityFilter.java reveals system data or debug information by calling write() on line 50. The information revealed by write() could help an adversary form a plan of attack.
An external information leak occurs when system data or debug information leaves the program to a remote machine via a socket or network connection. External leaks can help an attacker by revealing specific data about the operating system, full pathnames, the existence of usernames, or locations of configuration files, and are more serious than internal information leaks, which are more difficult for an attacker to access.
Can I get a custom JSON response without using httpServletResponse.getWriter().write(responseJson); or how to resolve the Fortify issue?
I managed to fix the issue by sanitizing the request and response using Jsoup library.
Maven dependency
Changed the following lines
Request
to
Response
to