isopach
isopach

Reputation: 1928

Prevent WebSocket Request from adding default headers

I'm writing a websocket client to connect to a server which I do not have the source code for (black box testing).

When I try to connect to the server with the following code, the default headers keep getting added to the request, and as a result it fails due to the specs of RFC 6455 only allowing a single Sec-WebSocket-Key to be used in the header.

socket_key = "Sec-WebSocket-Key: " + r.headers['Sec-WebSocket-Accept']

websocket.enableTrace(True)
ws = create_connection('wss://example.com/socket.io/?EIO=3&transport=websocket', headers=[socket_key])

However, this request is being sent instead:

--- request header ---
GET /socket.io/?EIO=3&transport=websocket HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Host: example.com
Origin: http://example.com
Sec-WebSocket-Key: <Generated WebSocket Key>
Sec-WebSocket-Version: 13
Sec-WebSocket-Key: <socket_key from above>

How can I prevent the first Sec-WebSocket-Key header from appearing, or replace its generated WebSocket key in the request with my own WebSocket key?

Upvotes: 0

Views: 718

Answers (1)

Darren Smith
Darren Smith

Reputation: 2488

Pass in a dictionary instead of a list, for the header argument:

my_header = { "Sec-WebSocket-Key" : "12345abcde" }
ws = websocket.create_connection("ws://127.0.0.1:8000/", header = my_header)

For this code, I see the following outbound request:

websocket:--- request header ---
GET / HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Host: 127.0.0.1:8000
Origin: http://127.0.0.1:8000
Sec-WebSocket-Version: 13
Sec-WebSocket-Key: 12345abcde

Upvotes: 1

Related Questions