Cross-Site Request Forgery in NodeJS
Prevention
Node.js does not provide built-in protection against CSRF attacks. Developers need to implement it manually by checking anti-CSRF tokens or use one of the many well-tested libraries and frameworks.
Socket.IO
WebSockets are not subject to the same-origin policy in the same way as regular HTTP requests. In this scenario, a victim follows a malicious link while authenticated on the target application. The malicious web page then establishes a WebSocket connection to the target endpoint (this is possible because the request carries authentication cookies). Finally, the malicious web page can read and write messages on the WebSocket.
Before V3, a Socket.IO server accepted connections from any HTTP origin, rendering web applications vulnerable to Cross-Site WebSocket Hijacking (CSWSH). Since V3, you need to explicitly enable Cross-Origin Resource Sharing (CORS). To do so, you might use Socket.IO server options to limit the allowed origins to a predefined subset:
const io = new Server(httpServer, {
cors: {
origin: ["https://example.com"]
}
});
Of course, this should be coupled with usual authentication, since nothing prevents a non-browser application from placing arbitrary content in the Origin HTTP header.
See Cross-Site WebSocket Hijacking (CSWSH) for more information.
References
OWASP - Cross-Site Request Forgery Cheat Sheet MITRE - CWE 352