# Avoiding XSS

## Synchronizer Tokens

Add hidden tokens to forms so that **every post requires the correct token**.

* Token is random and unique for each form.
* Server-side code verifies if the correct token is provided.

Why?

* If a script makes a direct POST it will not have access to the latest token.

```html
<form>
    <input type=“text” name=“login”></input>
    <input type=“password” name=“password”></input>
    <input type="hidden" name="csrf_token" value="KbyUmhTLMpYj7CD2di7JKP1P3qmLlkPt"/>
</form>
```

## Cookie-to-header

Upon the establishment of a session, a **cookie with a random value** is provided to the client.

The JS in the Client gets the cookie and resends the cookie in the header.

Why?

* Assumes that only JS provided on a specific HTTPS connection may access the cookie.
  * Assumes correct browser behavior.
  * The browser will not let a script called from an external source have access to external cookies.
  * SameSite=Lax will only allow using cookies from same requests (GET, not POST), in a top-level operation.
    * Top level operation: A click or something that changes the location.

Server will set:

```http
Set-Cookie: csrf_token=i8XNjC4b8KVok4uw; Expires=some_date; Max-Age=some_age; Path=/;
Domain=.site.org; SameSite=Lax; Secure
JS will call:
GET /index?csrf_token=i8XNjC4b8KVok4uw
```

## SameSite cookie attribute

Setting the SameSite to Strict instructs browser to **only provide the cookie to requests from that site**.

* Similar to Lax, but without exceptions to safe requests.

Why?

* If the SameSite is set, an external script will not have access to the token.

Server sets:

```http
Set-Cookie: csrf_token=i8XNjC4b8KVok4uw; Expires=some_date; Max-
Age=some_time; Path=/; Domain=.wikipedia.org; SameSite=Strict; Secure
```

Legit JS will have access to the cookie, External JS won’t.

## Double cookie submission

Two cookies are used.

* **Session Cookie**: identifies the user, stable across the session duration.
* **CSRF cookie**: dynamically changing for each request.

Why?

* External requests will not have information about the last CSRF cookie.
* May allow sites to force a specific interaction sequence as CSRF cookies may identify the previous location.
