XSS

Vulnerable Code:

Java Example:

@WebServlet("/search")
public class SearchServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String query = request.getParameter("q");
        PrintWriter out = response.getWriter();
        out.println("<html><body>");
        out.println("<h1>Search Results for: " + query + "</h1>");
        out.println("</body></html>");
    }
}

Reason for Vulnerability:

The user input (query) is directly embedded into the HTML output without any sanitization, allowing potential injection of malicious scripts.

Fixed Code:

javaCopyimport org.owasp.encoder.Encode;

@WebServlet("/search")
public class SearchServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String query = request.getParameter("q");
        PrintWriter out = response.getWriter();
        out.println("<html><body>");
        out.println("<h1>Search Results for: " + Encode.forHtml(query) + "</h1>");
        out.println("</body></html>");
    }
}

Reason for Fix:

The fixed code uses the OWASP Java Encoder library to properly encode the user input for HTML context, preventing XSS attacks.

Java Example

Vulnerable Code:

Reason for Vulnerability:

The Thymeleaf template uses th:utext to render the comment, which does not escape HTML entities, allowing potential XSS attacks.

Fixed Code:

Reason for Fix:

The fixed code uses th:text instead of th:utext in the Thymeleaf template. This automatically escapes HTML entities, preventing XSS attacks.

JavaScript Example

Vulnerable Code:

Reason for Vulnerability:

The user input (name) is directly inserted into the HTML response without any sanitization, allowing potential XSS attacks.

Fixed Code:

Reason for Fix:

The fixed code uses the escape-html package to sanitize the user input before inserting it into the HTML response, preventing XSS attacks.


Reflected XSS in JavaScript

Vulnerability: Reflected Cross-Site Scripting (XSS)

Vulnerable Code:

Reason for vulnerability: Directly inserting user input into the HTML without sanitization or encoding.

Fixed Code:

Reason for fix: Using innerText instead of innerHTML escapes the input, preventing XSS.


Stored XSS in Java

Vulnerability: Stored Cross-Site Scripting (XSS)

Vulnerable Code:

Reason for vulnerability: User input is directly displayed in the response without encoding, allowing malicious scripts to be executed.

Fixed Code:

Reason for fix: Escaping the user input using StringEscapeUtils.escapeHtml4 ensures that any HTML or JavaScript code in the input is neutralized.


Python (Flask)

Vulnerable Code:

Reason for vulnerability: User input is directly included in the response, allowing XSS.

Fixed Code:

Reason for fix: Escape user input before including it in the response.

Last updated