mirror of
https://github.com/Gabi-Zar/Pico-2W-Computer-Power-Controller.git
synced 2026-08-02 23:36:23 +02:00
Protect server against large content-length and slowloris
This commit is contained in:
26
main.py
26
main.py
@@ -173,7 +173,16 @@ async def wifi_watchdog():
|
|||||||
|
|
||||||
async def serve_client(reader, writer):
|
async def serve_client(reader, writer):
|
||||||
try:
|
try:
|
||||||
request_line = await reader.readline()
|
HEADER_TIMEOUT_MS = 5000
|
||||||
|
start = utime.ticks_ms()
|
||||||
|
|
||||||
|
try:
|
||||||
|
request_line = await asyncio.wait_for(reader.readline(), 5)
|
||||||
|
except asyncio.TimeoutError:
|
||||||
|
return
|
||||||
|
|
||||||
|
if utime.ticks_diff(utime.ticks_ms(), start) > HEADER_TIMEOUT_MS:
|
||||||
|
return
|
||||||
if not request_line:
|
if not request_line:
|
||||||
return
|
return
|
||||||
|
|
||||||
@@ -185,7 +194,12 @@ async def serve_client(reader, writer):
|
|||||||
|
|
||||||
content_length = 0
|
content_length = 0
|
||||||
while True:
|
while True:
|
||||||
header = await reader.readline()
|
if utime.ticks_diff(utime.ticks_ms(), start) > HEADER_TIMEOUT_MS:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
header = await asyncio.wait_for(reader.readline(), 5)
|
||||||
|
except asyncio.TimeoutError:
|
||||||
|
return
|
||||||
if header == b"\r\n":
|
if header == b"\r\n":
|
||||||
break
|
break
|
||||||
if header.lower().startswith(b"content-length:"):
|
if header.lower().startswith(b"content-length:"):
|
||||||
@@ -193,6 +207,14 @@ async def serve_client(reader, writer):
|
|||||||
|
|
||||||
message = ""
|
message = ""
|
||||||
|
|
||||||
|
if content_length > 256:
|
||||||
|
writer.write(
|
||||||
|
"HTTP/1.0 413 Payload Too Large\r\n"
|
||||||
|
"Connection: close\r\n\r\n"
|
||||||
|
)
|
||||||
|
await writer.drain()
|
||||||
|
return
|
||||||
|
|
||||||
if method == "POST" and path == "/computer" and content_length > 0:
|
if method == "POST" and path == "/computer" and content_length > 0:
|
||||||
body = await reader.read(content_length)
|
body = await reader.read(content_length)
|
||||||
params = parse_form(body.decode())
|
params = parse_form(body.decode())
|
||||||
|
|||||||
Reference in New Issue
Block a user