Lack of data validation - HTML code - Java

Lack of data validation - HTML code - Java

Need

Implementation of proper data validation for HTML code

Context

  • Usage of Java 8 for developing applications with enhanced features and performance
  • Usage of javax.servlet-api for building Java web applications with Servlets

Description

Non compliant code

        import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class DataServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String userContent = request.getParameter("userContent");
        response.setContentType("application/json");
        response.getWriter().write("{\\"message\\": \\"" + userContent + "\\"}");
    }
}
        
        

The above code represents a Servlet that accepts POST requests. The doPost method retrieves the parameter userContent from the request and directly embeds it into a JSON response without any form of validation or sanitization.

The vulnerability lies in the fact that the userContent parameter is directly embedded into the JSON response. This means that an attacker could potentially inject valid HTML code as the userContent parameter. When this JSON response is interpreted by a website, the injected HTML code would be executed.

For example, an attacker could send a POST request with the userContent parameter as . This would result in the following JSON response:

                {
  "message": ""
}

            


When this JSON response is interpreted by a website, the JavaScript code within the