---
title: Output Encoding Before Interpreter Use
impact: HIGH
impactDescription: prevents Cross-Site Scripting (XSS) and other injection attacks
tags: xss, encoding, output, html, security, kotlin
---

## Output Encoding Before Interpreter Use

Cross-Site Scripting (XSS) and other injection attacks occur when unescaped user data is sent back to the browser and interpreted as code. All output must be encoded based on the context in which it will be used (HTML, URL, JavaScript).

**Incorrect (no encoding):**

```kotlin
// XSS vulnerability in Ktor
get("/greet") {
    val name = call.parameters["name"]
    call.respondText("<h1>Hello, $name</h1>", ContentType.Text.Html) // XSS!
}

// Thymeleaf - using utext (unescaped text) with user input
// <div th:utext="${userInput}"></div>
```

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

```kotlin
// Thymeleaf - use th:text (automatically escapes HTML)
// <div th:text="${userInput}"></div>

// Using a library like OWASP Java Encoder
import org.owasp.encoder.Encode

val safeHtml = Encode.forHtml(untrustedInput)
val safeAttr = Encode.forHtmlAttribute(untrustedInput)
val safeJs = Encode.forJavaScript(untrustedInput)

// Ktor - Using HTML DSL (automatically escapes)
call.respondHtml {
    body {
        h1 { +"Hello, $name" } // "+" operator escapes content
    }
}

// Sanitizing HTML when you MUST allow some tags
val sanitizer = HtmlPolicyBuilder()
    .allowElements("b", "i", "u")
    .toFactory()
val cleanHtml = sanitizer.sanitize(untrustedHtml)
```

**Encoding by Context:**

| Context | Purpose | Recommended Encoder |
|---------|---------|---------------------|
| HTML Body | `<div>...</div>` | `Encode.forHtml()` |
| HTML Attribute | `<div title="...">` | `Encode.forHtmlAttribute()` |
| URL Parameter | `?q=...` | `URLEncoder.encode(s, "UTF-8")` |
| JavaScript | `var x = '...';` | `Encode.forJavaScript()` |
| CSS | `color: ...` | `Encode.forCssString()` |

**Tools:** OWASP Java Encoder, HTML Sanitizer (Guava), SonarQube (S5131)
