> ## Documentation Index
> Fetch the complete documentation index at: https://docs.esperr.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Cookies

> Managing cookie-based policies in Esper.

## What are Cookies?

Cookies are small pieces of data that websites store in your browser to remember information between visits. They're essential for keeping users logged in, storing preferences, and tracking sessions.

<Info>
  **MDN Web Docs**

  Read more on [HTTP cookies](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies).
</Info>

## Common Cookie Types

### Session Cookies

* **Purpose**: Temporary storage during browsing session
* **Examples**: `PHPSESSID`, `session_id`, `_session`
* **Lifetime**: Until browser closes
* **Security**: Critical for authentication

### Persistent Cookies

* **Purpose**: Remember users across visits
* **Examples**: `remember_me`, `user_preferences`
* **Lifetime**: Set expiration date
* **Security**: Can be convenience vs. security tradeoff

### Tracking Cookies

* **Purpose**: Analytics and advertising
* **Examples**: `_ga` (Google Analytics), `fbp` (Facebook)
* **Lifetime**: Often months or years
* **Security**: Privacy considerations

### Security Cookies

* **Purpose**: CSRF protection, security tokens
* **Examples**: `csrf_token`, `__Host-session`
* **Lifetime**: Varies by purpose
* **Security**: Critical for application security

## How Cookies Work on the Web

1. **Server sends cookie**: Via `Set-Cookie` header
2. **Browser stores it**: According to domain/path rules
3. **Browser sends it back**: On every matching request
4. **Server reads cookie**: To identify user/session

```
Request:  GET /dashboard
Response: Set-Cookie: session=abc123; HttpOnly; Secure
Next:     GET /profile (includes Cookie: session=abc123)
```

## Using Cookies in Policies

### Basic Examples

**Require authentication cookie:**

```yaml theme={null}
Field Type: Cookie
Field Reference: session_id
Operator: is not present
AND
Field Type: Request Path
Operator: starts with
Value: /account
Action: Block
```

**Detect cookie tampering:**

```yaml theme={null}
Field Type: Cookie
Field Reference: user_role
Operator: contains
Value: admin
Action: Challenge # Verify server-side
```

### Advanced Patterns

**Session fixation detection:**

```yaml theme={null}
Field Type: Cookie
Field Reference: session_id
Operator: equals
Value: FORCED_SESSION
Action: Block
```

**Rate limit by session:**

```yaml theme={null}
Field Type: Cookie
Field Reference: session_id
Operator: is present
Window: 5 minutes
Threshold: 100
Action: Challenge
```

<Warning>
  **Cookie Security**

  Never trust cookie values for authorization decisions! Cookies can be modified by users. Always verify server-side.
</Warning>

## Cookie Attributes That Matter

| Attribute | Purpose              | Security Impact            |
| --------- | -------------------- | -------------------------- |
| HttpOnly  | No JavaScript access | Prevents XSS theft         |
| Secure    | HTTPS only           | Prevents interception      |
| SameSite  | CSRF protection      | Limits cross-site sending  |
| Domain    | Scope control        | Prevents subdomain access  |
| Path      | URL restriction      | Limits cookie availability |

## Security Patterns

### Detecting Session Hijacking

```yaml theme={null}
# Sudden change in user agent with same session
Field Type: Cookie
Field Reference: session_id
Operator: is present
AND
User-Agent changed from previous request
Action: Challenge
```

### Preventing Cookie Stuffing

```yaml theme={null}
# Too many cookies might indicate attack
Field Type: Cookie (count)
Operator: greater than
Value: 50
Action: Block
```

### Invalid Cookie Formats

```yaml theme={null}
# Detect malformed session cookies
Field Type: Cookie
Field Reference: session_id
Operator: not matches regex
Value: ^[a-zA-Z0-9]{32}$
Action: Block
```

## Best Practices

### DO:

* **Validate cookie formats** - Ensure expected structure
* **Monitor cookie combinations** - Unusual sets might indicate attacks
* **Track cookie age** - Very old sessions might be compromised
* **Check cookie presence** - Missing auth cookies on protected resources
* **Use with other signals** - Combine with IP, user agent for better detection

### DON'T:

* **Trust cookie values** - Users can modify them
* **Store sensitive data** - Even encrypted, it's risky
* **Block missing cookies carelessly** - Some pages don't need them
* **Ignore cookie size** - Large cookies can cause issues
* **Forget about subdomains** - Cookie scope matters

## Common Attack Patterns

### Cookie Poisoning

```yaml theme={null}
Field Type: Cookie
Field Reference: cart_items
Operator: contains
Value: <script
Action: Block
```

### Privilege Escalation

```yaml theme={null}
Field Type: Cookie
Field Reference: is_admin
Operator: is present
Action: Block # If set client-side
```

### Session Fixation

```yaml theme={null}
Field Type: Cookie
Field Reference: session_id
Operator: in list
Value: [known_fixed_sessions]
Action: Block
```

## Working with Authentication

### Multi-Factor Authentication Check

```yaml theme={null}
# Require MFA cookie for sensitive actions
Field Type: Request Path
Operator: starts with
Value: /admin
AND
Field Type: Cookie
Field Reference: mfa_verified
Operator: not equals
Value: true
Action: Challenge
```

### Remember Me Security

```yaml theme={null}
# Limit "remember me" cookie actions
Field Type: Cookie
Field Reference: remember_token
Operator: is present
AND
Field Type: Request Path
Operator: equals
Value: /change-password
Action: Challenge  # Require fresh login
```

## Cookie Forensics

<Info>
  **Investigation Tips**

  When investigating suspicious activity:

  1. Check cookie creation time vs. activity time
  2. Look for impossible cookie combinations
  3. Compare cookie values with server records
  4. Track cookie modifications over time
</Info>

## Browser Behavior Quirks

### Third-Party Cookies

* Increasingly blocked by browsers
* May not be sent in embedded contexts
* Consider when building policies

### Cookie Limits

* \~4KB per cookie
* \~50 cookies per domain
* Browsers handle limits differently

## Troubleshooting

**"Cookie policy not matching"**

* Check exact cookie name (case-sensitive)
* Verify cookie is sent on this path
* Confirm domain/subdomain scope
* Check SameSite restrictions

**"Blocking legitimate users"**

* Users might have cookies disabled
* Private browsing affects cookies
* Cookie might be expired
* Browser extensions might block cookies

## Integration Patterns

### Combine with IP Tracking

```yaml theme={null}
# Detect session sharing
Field Type: Cookie
Field Reference: session_id
Operator: is present
AND
Field Type: Client IP
Changed from last request with same session
Action: Challenge
```

### API vs. Browser Detection

```yaml theme={null}
# APIs shouldn't have browser cookies
Field Type: Cookie
Field Reference: _ga
Operator: is present
AND
Field Type: Request Path
Operator: starts with
Value: /api
Action: Monitor  # Suspicious
```

## Related Fields

* [Headers](./headers) - Cookies are sent via Cookie header
* [Client IP](./client-ip) - Often checked together for session security
* [User Agent](./user-agent) - Changes might indicate session hijacking
* [Request Path](./request-path) - Different paths need different cookies
