# Origin Checks and Cross-Site WebSocket Hijacking — WebSockets & Server-Sent Events

Source: https://www.skillbyai.com/en/realtime-web/rt-cswsh

> Explain cross-site WebSocket hijacking and defend against it with Origin allow-lists and CORS for SSE.

## The same-origin policy does not protect WebSockets

Browsers let any web page open a WebSocket to **any** host; the same-origin policy and CORS do not apply to the WebSocket handshake. If your server authenticates with cookies, an attacker's page at `evil.example` can open `wss://your-app/ws`, and the browser will attach your user's cookies. The attacker's script can then read messages and send commands as the victim. This is **Cross-Site WebSocket Hijacking (CSWSH)**, essentially CSRF with a two-way channel. The defence is to check the **`Origin`** header during the upgrade against an allow-list of your own front-end origins and refuse others. Browsers set `Origin` themselves and page scripts cannot forge it. Non-browser clients can send any Origin, so the check protects your users' browsers, not your API from scripts; that is what authentication is for. `SameSite` cookies add defence in depth. SSE, being a normal request, follows CORS rules, so do not reflect arbitrary origins in `Access-Control-Allow-Origin` together with credentials.

## A strict Origin allow-list

Compare against exact origins. Substring or `endsWith` checks are easy to bypass with domains like `app.example.in.evil.example`.

```js
const ALLOWED = new Set(['https://app.example.in', 'https://admin.example.in']);

function originAllowed(origin) {
  return ALLOWED.has(origin);
}

console.log(originAllowed('https://app.example.in'));
console.log(originAllowed('https://app.example.in.evil.example'));
console.log(originAllowed(undefined));
```

Output:

```
true
false
false
```

## A guard who checks the visitor's sender

A hostel guard lets in anyone who shows a resident's ID card. A stranger who borrowed the card while the resident slept still gets in. Checking who sent the visitor, the Origin, stops strangers using a resident's card on their behalf.

## Do not trust Origin from non-browser clients

A Python script can set `Origin` to anything. Origin checks stop a malicious page from abusing a logged-in user's browser; they are not a replacement for authenticating every connection.

**Quiz:** Your WebSocket server authenticates with session cookies and has no Origin check. What can a malicious website do?

- [ ] Nothing, because the same-origin policy blocks cross-site WebSockets
- [ ] Only read your server's TLS certificate
- [x] Open a WebSocket to your server with the victim's cookies and act as the victim
- [ ] Change the victim's cookies to its own domain

*Answer:* Open a WebSocket to your server with the victim's cookies and act as the victim. Cross-origin WebSocket connections are allowed and carry cookies. Without an Origin check, the attacker's page gets an authenticated two-way channel: CSWSH.
