Modern Apps git

← Modern-Apps.git

library: reject negative WebSocket frame lengths

Commit
365a57e819a2dd9dcafee9a60746f25a0daeeb29
Author
Vayun Mathur <[email protected]>
When
2026-11-19 01:54 UTC (17 days ago)
Parents
f6f6e2c
A peer can set the high bit of the 64-bit frame length, making
the parsed payload length negative. readFramePayload only
checked for lengths above Int.MAX_VALUE, so a negative length
reached ByteArray allocation as NegativeArraySizeException.
That is a RuntimeException, not an IOException, so it escaped
the read loop's error handling and crashed the collecting
coroutine instead of cleanly ending the socket. Negative
lengths now fail with IOException like oversized frames.

Verified: ./gradlew :library:network:testDebugUnitTest and
./check library/network pass.

Diff

library/network/src/main/java/com/vayunmathur/library/network/WebSocketClient.kt
diff --git a/library/network/src/main/java/com/vayunmathur/library/network/WebSocketClient.kt b/library/network/src/main/java/com/vayunmathur/library/network/WebSocketClient.ktindex be9030062e..25e2908bf3 100644--- a/library/network/src/main/java/com/vayunmathur/library/network/WebSocketClient.kt+++ b/library/network/src/main/java/com/vayunmathur/library/network/WebSocketClient.kt@@ -258,7 +258,12 @@ class WebSocketClient private constructor(     }      private fun readFramePayload(header: FrameHeader): ByteArray {-        if (header.payloadLen > Int.MAX_VALUE) throw IOException("ws frame too large ${header.payloadLen}")+        // A hostile/buggy peer can send a negative 64-bit length (high bit set);+        // without this it becomes NegativeArraySizeException, which is not an+        // IOException and escapes the read loop's error handling as a crash.+        if (header.payloadLen < 0 || header.payloadLen > Int.MAX_VALUE) {+            throw IOException("ws frame too large ${header.payloadLen}")+        }         val payload = readExactBytes(header.payloadLen.toInt(), "ws truncated frame")         val maskKey = header.maskKey ?: return payload         for (i in payload.indices) {