NIOWebSocket: reject 8-byte payload lengths that exceed Int.max (#3603)

RFC 6455 §5.2 specifies that when the payload length indicator byte is
127, the following 8 bytes hold a 64-bit unsigned integer and the most
significant bit of that integer must be 0. The maximum legal value is
therefore 0x7FFFFFFFFFFFFFFF, which equals Int.max on all 64-bit
platforms Swift supports.

WSParser.parseStep read the raw UInt64 and passed it directly to Int()
without a bounds check. Swift's Int initializer performs a checked
conversion and traps on overflow, so any remote peer that sends a single
WebSocket frame with the MSB of the 8-byte length set will cause a fatal
error in the receiving process. No authentication is required; the frame
is processed before any application handler runs.

The fix adds a guard that rejects the frame with
NIOWebSocketError.invalidFrameLength before the conversion, which is the
same error path used for frames that exceed maxFrameSize. The call site
in decode() is updated to propagate the throw.

A regression test covers the exact byte sequence that previously caused
the fatal trap.

Co-authored-by: g0w6y <g0w6y@users.noreply.github.com>
Co-authored-by: Cory Benfield <lukasa@apple.com>
This commit is contained in:
authored and GitHub committed 2026-05-26 15:35:59 +01:00
1 parent d20fa05a64
commit 4e370dc4d7
2 files changed
+25 -4

No files matched your search

@@ -108,7 +108,7 @@ struct WSParser {
/// The current state of the decoder during incremental parse.
var state: DecoderState = .idle
mutating func parseStep(_ buffer: inout ByteBuffer) -> ParseResult {
mutating func parseStep(_ buffer: inout ByteBuffer) throws -> ParseResult {
switch self.state {
case .idle:
// This is a new buffer. We want to find the first octet and save it off.
@@ -160,10 +160,14 @@ struct WSParser {
return .insufficientData
}
guard lengthQWord <= UInt64(Int.max) else {
throw NIOWebSocketError.invalidFrameLength
}
let length = Int(lengthQWord)
if masked {
self.state = .waitingForMask(firstByte: firstByte, length: Int(lengthQWord))
self.state = .waitingForMask(firstByte: firstByte, length: length)
} else {
self.state = .waitingForData(firstByte: firstByte, length: Int(lengthQWord), maskingKey: nil)
self.state = .waitingForData(firstByte: firstByte, length: length, maskingKey: nil)
}
return .continueParsing
@@ -261,7 +265,7 @@ public final class WebSocketFrameDecoder: ByteToMessageDecoder {
// rely on that: sometimes we have zero-length elements to parse, and the caller doesn't
// guarantee to call us with zero-length bytes.
while true {
switch parser.parseStep(&buffer) {
switch try parser.parseStep(&buffer) {
case .result(let frame):
context.fireChannelRead(WebSocketFrameDecoder.wrapInboundOut(frame))
return .continue