This repository has been archived by the owner on Dec 17, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
websocket_poc_server.py
67 lines (54 loc) · 1.72 KB
/
websocket_poc_server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Author:
Marcus Voß (m.voss@laposte.net)
Description:
POC websocket server that prints every message it receives.
"""
import asyncio
import json
import websockets
import logging
logging.basicConfig(level=logging.INFO)
CLIENTS = set()
WEBSOCKET_IP = "127.0.0.1" # "10.0.20.227"
WEBSOCKET_PORT = 5678
USERNAME = "MVO"
PASSWORD = "e5W7Avnr6NgUiZ"
async def authenticate(username, password):
reason = "unknown reason"
if username == USERNAME:
if password == PASSWORD:
return True
else:
reason = f"wrong password ({password})"
else:
reason = f"wrong username ({username})"
logging.info(f"client refused: {reason}")
return False
async def register(websocket):
logging.info("client connected {websocket}")
CLIENTS.add(websocket)
async def unregister(websocket):
logging.info("client disconnected {websocket}")
CLIENTS.remove(websocket)
async def server(websocket, path):
logging.debug("websocket: {websocket}")
logging.debug("path: {path}")
await register(websocket)
try:
async for message in websocket:
msg = json.loads(message)
uuid = websocket.request_headers["uuid"] or "unknown"
msgID = msg.get("msgID")
logging.info(f"{uuid}> {msgID}")
await websocket.send(f"OK {msgID}")
finally:
await unregister(websocket)
logging.info("waiting for clients...")
start_server = websockets.serve(server, WEBSOCKET_IP, WEBSOCKET_PORT, create_protocol=websockets.basic_auth_protocol_factory(
realm="TUB", check_credentials=authenticate)
)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()