Implementation of proper data validation for HTML 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": ""
}