In this lesson, you will learn how to sanitize WebSocket handshake headers to prevent injection attacks and mitigate session fixation vulnerabilities.
When a client initiates a WebSocket connection, it sends an HTTP Upgrade request containing headers and cookies. Because these headers are often used to identify the user session, they are prime targets for malicious actors. If you blindly trust incoming headers, an attacker might inject malicious data into your application logs, database queries, or server-side state, or attempt to hijack a session by manipulating cookie values during the handshake.
Sanitizing the Handshake
To secure your connection, you must validate and sanitize these inputs during the handshake phase—before the socket connection is fully established. In socket.io (or standard ws), you can intercept the connection attempt using middleware.
Here is how you can inspect and clean the incoming request:
io.use((socket, next) => {
const userAgent = socket.handshake.headers['user-agent'];
const sessionCookie = socket.handshake.headers.cookie;
// 1. Sanitize against injection by stripping unexpected characters
const cleanAgent = userAgent ? userAgent.replace(/[^\w\s./-]/gi, '') : 'unknown';
// 2. Validate session cookie structure
if (!sessionCookie || !isValidFormat(sessionCookie)) {
return next(new Error('Authentication error: Invalid session header'));
}
// Attach sanitized data to the socket object for later use
socket.data.userAgent = cleanAgent;
next();
});
Preventing Session Fixation
Session fixation occurs when an attacker provides a known session identifier to a victim. During the handshake, you should verify that the provided cookie is tied to a legitimate session stored in your server-side cache (e.g., Redis). If the cookie does not match the expected patterns or fails a cryptographic integrity check, reject the connection immediately using next(new Error()).
By strictly validating the Origin header to prevent Cross-Site WebSocket Hijacking (CSWH) and ensuring your cookies are marked as HttpOnly and Secure, you create a defensive perimeter that protects your real-time infrastructure from unauthorized access.
Key Takeaway: Always treat WebSocket handshake headers as untrusted input by sanitizing strings and validating session identifiers before allowing the connection to upgrade.