From e41172ca57fe4b61edea5983ae588d3ab20ebff0 Mon Sep 17 00:00:00 2001 From: ducklet Date: Sun, 31 Jan 2021 00:37:49 +0100 Subject: [PATCH] improve ws connection spam filter --- dev/config.js | 2 +- quiz/quiz.py | 20 +++++++++++--------- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/dev/config.js b/dev/config.js index 8577cba..1d9ac1f 100644 --- a/dev/config.js +++ b/dev/config.js @@ -1,3 +1,3 @@ export default { - wsurl: "ws://docker.local:8765", + wsurl: "ws://docker.local:8765/quiz", } diff --git a/quiz/quiz.py b/quiz/quiz.py index 5180635..0d2d0ec 100644 --- a/quiz/quiz.py +++ b/quiz/quiz.py @@ -2,6 +2,7 @@ import asyncio import logging import unicodedata from dataclasses import dataclass, field +from http import HTTPStatus from json import dumps, loads from secrets import compare_digest, token_hex from time import perf_counter_ns @@ -304,14 +305,6 @@ async def juggle(client: Client): async def connected(ws: Websocket, path: str): - # We'll throw out anything not starting with a certain path prefix just to - # get rid of internet spam - mass scans for security problems, etc. - # No need to waste resources on this kinda crap. - # Ideally the same rule should already be enforced by an upstream proxy. - if not path.startswith(config.path_prefix): - await ws.close() - return - path = printable(path) client = Client(ws, path) @@ -344,5 +337,14 @@ async def connected(ws: Websocket, path: str): log.info("[%s] session gone: %s", client, session) +async def check_path(path: str, request_headers) -> Optional["websockets.HTTPResponse"]: + # We'll throw out anything not starting with a certain path prefix just to + # get rid of internet spam - mass scans for security problems, etc. + # No need to waste resources on this kinda crap. + # Ideally the same rule should already be enforced by an upstream proxy. + if not path.startswith(config.path_prefix): + return (HTTPStatus.FORBIDDEN, {}, b"") + + def server(host: str, port: int): - return websockets.serve(connected, host, port) + return websockets.serve(connected, host, port, process_request=check_path)