पाठ 25 / 32
Origin Checks and Cross-Site WebSocket Hijacking
यह पाठ अभी हिंदी में अनुवादित नहीं है, इसलिए अंग्रेज़ी में दिखाया जा रहा है।
Explain cross-site WebSocket hijacking and defend against it with Origin allow-lists and CORS for SSE.
लेखक: Rahul Agarwal · 15 साल से वेब डेवलपर
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.
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.
त्वरित जाँच: 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
- 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.