Skip to content

Commit 411a71f

Browse files
committed
fix(server): to increase security allow only websocket connections from same origin as the webclient is served
1 parent 10df994 commit 411a71f

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

server/ws.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
import json
2+
import sys
23

34
from starlette.datastructures import State
45
from starlette.endpoints import WebSocketEndpoint
56
from starlette.websockets import WebSocket
7+
from urllib.parse import urlparse
68

79
ws_actions = {}
810

@@ -38,6 +40,21 @@ async def send_json(websocket: WebSocket, action: str, json_payload):
3840

3941

4042
class WebSocketHandler(WebSocketEndpoint):
43+
async def on_connect(self, websocket: WebSocket):
44+
# check for same request origin of webclient url and websocket opener
45+
# (needed because websocket isn't affected by CORS)
46+
origin = urlparse(websocket.headers.get('origin'))
47+
host = websocket.url
48+
if origin.netloc and host.netloc and origin.netloc == host.netloc:
49+
if origin.scheme != 'https':
50+
print('Insecure HTTP request detected. Please serve the application via HTTPS.', file=sys.stderr)
51+
await websocket.accept()
52+
else:
53+
print('Cross-Site WebSocket Hijacking detected. '
54+
'If the application is served behind a reverse-proxy, you maybe forgot to pass the host header.',
55+
file=sys.stderr)
56+
await websocket.close()
57+
4158
async def on_receive(self, websocket: WebSocket, data):
4259
body = json.loads(data)
4360
action, payload = body['request'], body.get('payload', {})

0 commit comments

Comments
 (0)