---
title: Escape Data By Output Context
impact: MEDIUM
impactDescription: ensures data is safely encoded for its specific target environment (HTML, JavaScript, URL, etc.)
tags: xss, escaping, context, encoding, security, kotlin
---

## Escape Data By Output Context

Using the wrong escaping strategy is as dangerous as not escaping at all. For example, HTML entity encoding (like `&lt;`) in a JavaScript string context will not prevent an attacker from breaking out of the string.

**Incorrect (wrong encoding for context):**

```kotlin
// WRONG: Using HTML escaping for a JavaScript variable
val escaped = HtmlUtils.htmlEscape(userInput)
val responseHtml = "<script>var name = '$escaped';</script>" 
// Still vulnerable to breaking out of the quote if userInput contains ' or \

// WRONG: No header sanitization
response.setHeader("X-User-Note", userInput) 
// Potential HTTP Header Injection (CRLF injection)
```

**Correct (context-appropriate encoding):**

```kotlin
import org.owasp.encoder.Encode
import java.net.URLEncoder

// 1. HTML Content Context (Normal text inside tags)
val safeHtml = Encode.forHtml(userInput)
val pTag = "<p>$safeHtml</p>"

// 2. JavaScript Context (User data inside a script tag)
val safeJsValue = Encode.forJavaScript(userInput)
val script = "<script>var username = '$safeJsValue';</script>"

// 3. URL Parameter Context (Used in a query string)
val safeUrlParam = URLEncoder.encode(userInput, "UTF-8")
val redirectUrl = "/search?q=$safeUrlParam"

// 4. HTTP Header Context (Preventing CRLF injection)
val safeHeader = userInput.replace("[\r\n]".toRegex(), "")
response.setHeader("X-Custom-Data", safeHeader)

// 5. Email Header Context
val safeSubject = emailSubject.replace("[\r\n]".toRegex(), "")
```

**Context Rules:**
- **Inside HTML body:** Use HTML Entity encoding.
- **Inside HTML attribute:** Use HTML Attribute encoding.
- **Inside `<script>` tags:** Use JavaScript literal encoding or JSON stringification.
- **Inside CSS:** Use CSS hex escaping.
- **Inside URL:** Use URL encoding (percent-encoding).

**Tools:** OWASP Java Encoder (Recommended), Spring `HtmlUtils`, Ktor `encodeURLQueryComponent`, SonarQube (S2245)
