---
title: Use __Host- Prefix For Cookies
impact: MEDIUM
impactDescription: locks the cookie to the specific domain and path, preventing subdomain cookie tossing attacks
tags: cookies, prefix, domain, security, kotlin
---

## Use __Host- Prefix For Cookies

The `__Host-` prefix is a browser-enforced security mechanism. When a cookie name starts with `__Host-`, the browser will only accept it if it meets strict criteria, making it much harder for an attacker on a subdomain (e.g., `attacker.example.com`) to overwrite or spoof cookies for the main domain (`example.com`).

**Incorrect (standard session cookie):**

```kotlin
// VULNERABLE to subdomain shadowing/tossing
val cookie = Cookie("session_id", token).apply {
    isHttpOnly = true
    isSecure = true
    path = "/"
}
```

**Correct (__Host- prefixed cookie):**

```kotlin
// STRONGLY SECURE
val cookie = Cookie("__Host-session_id", token).apply {
    isHttpOnly = true
    isSecure = true // REQ: Must be secure
    path = "/"      // REQ: Must be /
    // REQ: Must NOT call setDomain(). 
    // This locks it to the EXACT host that sent it.
}
response.addCookie(cookie)

// Ktor:
call.sessions.set("__Host-session", MySession(token))
// Ensure the session cookie configuration has path = "/" and secure = true
```

**__Host- Prefix Requirements:**
1.  Must have the `Secure` flag.
2.  Must be sent from a secure origin (HTTPS).
3.  Must have `Path=/`.
4.  Must **NOT** have a `Domain` attribute (this ensures it's only sent to the host that set it, not subdomains).

**Why use it?**
It prevents "Cookie Tossing" attacks where an attacker controlling a subdomain (like `blog.company.com`) sets a cookie for the parent domain (`company.com`), potentially hijacking its sessions or triggering CSRF.

**Tools:** OWASP ZAP, Browser DevTools, Snyk, Manual Review
