# XSS

#### Vulnerable Code:

Java Example:

```java
@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:

```java
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:

```java
javaCopy@Controller
public class CommentController {
    @PostMapping("/addComment")
    public String addComment(@RequestParam String comment, Model model) {
        model.addAttribute("latestComment", comment);
        return "comments";
    }
}

<!-- comments.html -->
<div th:utext="${latestComment}"></div>
```

#### 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:

```java
javaCopy@Controller
public class CommentController {
    @PostMapping("/addComment")
    public String addComment(@RequestParam String comment, Model model) {
        model.addAttribute("latestComment", comment);
        return "comments";
    }
}

<!-- comments.html -->
<div th:text="${latestComment}"></div>
```

#### 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:

```javascript
javascriptCopyconst express = require('express');
const app = express();

app.get('/welcome', (req, res) => {
    const name = req.query.name;
    res.send(`<h1>Welcome, ${name}!</h1>`);
});

app.listen(3000, () => console.log('Server running on port 3000'));
```

#### Reason for Vulnerability:

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

#### Fixed Code:

```javascript
javascriptCopyconst express = require('express');
const escapeHtml = require('escape-html');
const app = express();

app.get('/welcome', (req, res) => {
    const name = req.query.name;
    res.send(`<h1>Welcome, ${escapeHtml(name)}!</h1>`);
});

app.listen(3000, () => console.log('Server running on port 3000'));
```

#### 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:**

```javascript
javascriptCopy codeconst userInput = getParameterByName('input');
document.getElementById('output').innerHTML = userInput;
```

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

**Fixed Code:**

```javascript
javascriptCopy codeconst userInput = getParameterByName('input');
document.getElementById('output').innerText = userInput;
```

**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:**

```java
javaCopy codeString comment = request.getParameter("comment");
response.getWriter().println(comment);
```

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

**Fixed Code:**

```java
javaCopy codeString comment = request.getParameter("comment");
response.getWriter().println(StringEscapeUtils.escapeHtml4(comment));
```

**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:**

```python
pythonCopy code@app.route('/greet')
def greet():
    name = request.args.get('name')
    return f'Hello {name}'
```

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

**Fixed Code:**

```python
pythonCopy code@app.route('/greet')
def greet():
    name = request.args.get('name')
    return f'Hello {escape(name)}'
```

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