|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""DoS hardening regression tests. |
| 3 | +
|
| 4 | +Covers crashes that a single malicious request could trigger before the |
| 5 | +hardening fixes: |
| 6 | +
|
| 7 | +1. Deeply nested JSON body -> RecursionError. json.loads() raises |
| 8 | + RecursionError (a RuntimeError subclass), which is neither ValueError |
| 9 | + nor ClientError, so it used to propagate out of wait() and crash the |
| 10 | + server loop. Now caught and turned into 400. |
| 11 | +2. WebSocket auto-pong when the send buffer cap is hit -> OSError. The |
| 12 | + automatic pong reply lives deep inside _ws_process_buffer(); an OSError |
| 13 | + from the send-buffer cap (slow/dead consumer, ping flood) used to |
| 14 | + escape the event loop. Now it closes the connection instead. |
| 15 | +3. Custom/unknown response status code -> KeyError in the status line. |
| 16 | + Now tolerated via STATUS_CODES.get(). |
| 17 | +""" |
| 18 | +import errno |
| 19 | +import socket |
| 20 | +import threading |
| 21 | +import time |
| 22 | +import unittest |
| 23 | + |
| 24 | +from uhttp import server as uhttp_server |
| 25 | +from uhttp.server import ( |
| 26 | + HttpConnection, EVENT_WS_CLOSE, EVENT_WS_PING, WS_OPCODE_PING, |
| 27 | +) |
| 28 | +from tests.test_websocket import build_masked_frame |
| 29 | + |
| 30 | + |
| 31 | +class TestDeepJsonNoCrash(unittest.TestCase): |
| 32 | + """A deeply nested JSON body must yield 400, not crash the loop.""" |
| 33 | + |
| 34 | + PORT = 9958 |
| 35 | + crash = None |
| 36 | + |
| 37 | + @classmethod |
| 38 | + def setUpClass(cls): |
| 39 | + cls.server = uhttp_server.HttpServer(port=cls.PORT) |
| 40 | + cls._stop = False |
| 41 | + |
| 42 | + def run(): |
| 43 | + while not cls._stop and cls.server: |
| 44 | + try: |
| 45 | + client = cls.server.wait(timeout=0.1) |
| 46 | + except Exception as err: # pylint: disable=broad-except |
| 47 | + # An unhandled exception here means the malicious |
| 48 | + # request escaped request processing and killed the |
| 49 | + # loop — exactly the bug under test. |
| 50 | + cls.crash = repr(err) |
| 51 | + break |
| 52 | + if client: |
| 53 | + client.respond({'ok': True}) |
| 54 | + |
| 55 | + cls._thread = threading.Thread(target=run, daemon=True) |
| 56 | + cls._thread.start() |
| 57 | + time.sleep(0.3) |
| 58 | + |
| 59 | + @classmethod |
| 60 | + def tearDownClass(cls): |
| 61 | + cls._stop = True |
| 62 | + if cls.server: |
| 63 | + cls.server.close() |
| 64 | + cls._thread.join(timeout=2) |
| 65 | + |
| 66 | + def _request(self, body, content_type=b'application/json'): |
| 67 | + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 68 | + sock.connect(('localhost', self.PORT)) |
| 69 | + sock.sendall( |
| 70 | + b"POST /x HTTP/1.1\r\n" |
| 71 | + b"Host: localhost\r\n" |
| 72 | + b"Content-Type: " + content_type + b"\r\n" |
| 73 | + b"Content-Length: " + str(len(body)).encode() + b"\r\n" |
| 74 | + b"Connection: close\r\n" |
| 75 | + b"\r\n" + body) |
| 76 | + sock.settimeout(3.0) |
| 77 | + data = b"" |
| 78 | + while True: |
| 79 | + try: |
| 80 | + chunk = sock.recv(4096) |
| 81 | + except socket.timeout: |
| 82 | + break |
| 83 | + if not chunk: |
| 84 | + break |
| 85 | + data += chunk |
| 86 | + sock.close() |
| 87 | + return data |
| 88 | + |
| 89 | + def test_deep_json_returns_400_and_survives(self): |
| 90 | + """~100k-deep JSON array: server answers 400 and stays alive.""" |
| 91 | + depth = 100000 |
| 92 | + body = b'[' * depth + b']' * depth # valid but pathologically deep |
| 93 | + response = self._request(body) |
| 94 | + self.assertIn(b"400", response, "deep JSON should be rejected as 400") |
| 95 | + self.assertIsNone( |
| 96 | + self.crash, f"server loop crashed: {self.crash}") |
| 97 | + |
| 98 | + # Prove the loop is still serving requests after the attack. |
| 99 | + good = self._request(b'{"a":1}') |
| 100 | + self.assertIn(b"200", good, "server stopped serving after deep JSON") |
| 101 | + self.assertIsNone(self.crash, f"server loop crashed: {self.crash}") |
| 102 | + |
| 103 | + |
| 104 | +class TestCustomStatusCode(unittest.TestCase): |
| 105 | + """respond() with a status not in STATUS_CODES must not raise.""" |
| 106 | + |
| 107 | + PORT = 9959 |
| 108 | + |
| 109 | + def test_unknown_status_code(self): |
| 110 | + server = uhttp_server.HttpServer(port=self.PORT) |
| 111 | + stop = {'v': False} |
| 112 | + loop_error = {'v': None} |
| 113 | + |
| 114 | + def run(): |
| 115 | + while not stop['v'] and server._socket is not None: |
| 116 | + try: |
| 117 | + client = server.wait(timeout=0.1) |
| 118 | + except Exception as err: # pylint: disable=broad-except |
| 119 | + loop_error['v'] = repr(err) |
| 120 | + break |
| 121 | + if client: |
| 122 | + client.respond(data="custom", status=250) |
| 123 | + |
| 124 | + thread = threading.Thread(target=run, daemon=True) |
| 125 | + thread.start() |
| 126 | + time.sleep(0.3) |
| 127 | + try: |
| 128 | + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 129 | + sock.connect(('localhost', self.PORT)) |
| 130 | + sock.sendall( |
| 131 | + b"GET / HTTP/1.1\r\nHost: localhost\r\n" |
| 132 | + b"Connection: close\r\n\r\n") |
| 133 | + sock.settimeout(2.0) |
| 134 | + data = b"" |
| 135 | + while True: |
| 136 | + chunk = sock.recv(4096) |
| 137 | + if not chunk: |
| 138 | + break |
| 139 | + data += chunk |
| 140 | + sock.close() |
| 141 | + # Status line present with the custom code, no KeyError crash. |
| 142 | + self.assertIn(b"250", data) |
| 143 | + self.assertTrue(data.startswith(b"HTTP/1.1 250")) |
| 144 | + self.assertIsNone(loop_error['v'], loop_error['v']) |
| 145 | + finally: |
| 146 | + stop['v'] = True |
| 147 | + server.close() |
| 148 | + thread.join(timeout=2) |
| 149 | + |
| 150 | + |
| 151 | +class _StalledSocket: |
| 152 | + """Socket whose send never drains (EAGAIN), to force the send-buffer |
| 153 | + cap to trip deterministically without any real network.""" |
| 154 | + |
| 155 | + def send(self, _data): |
| 156 | + raise OSError(errno.EAGAIN, "stalled") |
| 157 | + |
| 158 | + def recv(self, _n): |
| 159 | + raise OSError(errno.EAGAIN, "no data") |
| 160 | + |
| 161 | + def close(self): |
| 162 | + pass |
| 163 | + |
| 164 | + |
| 165 | +class _FakeServer: |
| 166 | + """Minimal server stub for constructing a bare HttpConnection.""" |
| 167 | + |
| 168 | + _trusted_proxies = None |
| 169 | + event_mode = True |
| 170 | + is_secure = False |
| 171 | + |
| 172 | + def remove_connection(self, connection): |
| 173 | + pass |
| 174 | + |
| 175 | + |
| 176 | +class TestWsPingFloodNoCrash(unittest.TestCase): |
| 177 | + """Auto-pong hitting the send-buffer cap closes instead of crashing.""" |
| 178 | + |
| 179 | + def test_ping_flood_send_cap_does_not_raise(self): |
| 180 | + conn = HttpConnection( |
| 181 | + _FakeServer(), _StalledSocket(), ('1.2.3.4', 1234), |
| 182 | + max_send_buffer_size=256) |
| 183 | + conn._ws_mode = True |
| 184 | + |
| 185 | + # Flood masked PING frames. Each auto-pong (~102 B) accumulates in |
| 186 | + # the (never-draining) send buffer; after a couple it exceeds the |
| 187 | + # 256 B cap and _send() raises OSError from inside the auto-pong. |
| 188 | + ping = build_masked_frame(WS_OPCODE_PING, b'x' * 100) |
| 189 | + conn._buffer.extend(ping * 20) |
| 190 | + |
| 191 | + events = [] |
| 192 | + for _ in range(50): |
| 193 | + try: |
| 194 | + ready = conn._ws_process_buffer() |
| 195 | + except OSError: |
| 196 | + self.fail( |
| 197 | + "auto-pong raised OSError — would crash the event loop") |
| 198 | + if not ready: |
| 199 | + break |
| 200 | + events.append(conn._event) |
| 201 | + if conn._event == EVENT_WS_CLOSE: |
| 202 | + break |
| 203 | + |
| 204 | + self.assertIn(EVENT_WS_PING, events, "expected some pings processed") |
| 205 | + self.assertIn( |
| 206 | + EVENT_WS_CLOSE, events, |
| 207 | + "send-cap overflow should close the WS, not crash") |
| 208 | + self.assertFalse(conn._ws_mode, "connection should leave WS mode") |
| 209 | + |
| 210 | + |
| 211 | +if __name__ == '__main__': |
| 212 | + unittest.main() |
0 commit comments