improve ws connection spam filter

This commit is contained in:
ducklet 2021-01-31 00:37:49 +01:00
parent 4908b1fc6e
commit e41172ca57
2 changed files with 12 additions and 10 deletions

View file

@ -1,3 +1,3 @@
export default { export default {
wsurl: "ws://docker.local:8765", wsurl: "ws://docker.local:8765/quiz",
} }

View file

@ -2,6 +2,7 @@ import asyncio
import logging import logging
import unicodedata import unicodedata
from dataclasses import dataclass, field from dataclasses import dataclass, field
from http import HTTPStatus
from json import dumps, loads from json import dumps, loads
from secrets import compare_digest, token_hex from secrets import compare_digest, token_hex
from time import perf_counter_ns from time import perf_counter_ns
@ -304,14 +305,6 @@ async def juggle(client: Client):
async def connected(ws: Websocket, path: str): 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) path = printable(path)
client = Client(ws, path) client = Client(ws, path)
@ -344,5 +337,14 @@ async def connected(ws: Websocket, path: str):
log.info("[%s] session gone: %s", client, session) 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): def server(host: str, port: int):
return websockets.serve(connected, host, port) return websockets.serve(connected, host, port, process_request=check_path)