Skip to content

wsproxy: add WithMaxReadMessageSize option to limit incoming WebSocket message size#45

Open
crawfordxx wants to merge 1 commit into
tmc:masterfrom
crawfordxx:feat-max-read-message-size
Open

wsproxy: add WithMaxReadMessageSize option to limit incoming WebSocket message size#45
crawfordxx wants to merge 1 commit into
tmc:masterfrom
crawfordxx:feat-max-read-message-size

Conversation

@crawfordxx

Copy link
Copy Markdown

Problem

Without a read-message-size limit, an unauthenticated client can send a
single arbitrarily large WebSocket message and force the proxy to buffer
the entire payload in memory before forwarding it upstream. This is a
memory-exhaustion DoS vector: in etcd, a 256 MiB WebSocket message causes
~1.26 GiB RSS growth (~5× amplification).

gorilla/websocket exposes conn.SetReadLimit(n) exactly for this purpose:
when an incoming message exceeds the limit the connection is closed with
WebSocket status 1009 (message too big) instead of buffering the full frame.

Fix

Add a WithMaxReadMessageSize(int64) Option that calls conn.SetReadLimit
immediately after the connection is upgraded:

wsproxy.WebsocketProxy(
    h,
    wsproxy.WithMaxReadMessageSize(int64(maxRequestBytes) * 4),
)

When the limit is ≤ 0 the behaviour is unchanged (gorilla/websocket default
of 32 MiB applies).

Why this belongs in wsproxy

The limit must be applied at the WebSocket layer, after the protocol upgrade
but before the first ReadMessage call. HTTP-level middleware (e.g.
http.MaxBytesReader) does not see WebSocket frame payloads because
gorilla/websocket reads directly from the raw TCP connection.

…t message size

Without a read-message limit, an unauthenticated client can send an
arbitrarily large WebSocket message and force the proxy to buffer the
entire payload in memory before forwarding it upstream. gorilla/websocket
exposes conn.SetReadLimit(n) exactly for this purpose: when a message
exceeds the limit it closes the connection with 1009 (message too big)
instead of reading the oversized frame.

Add a WithMaxReadMessageSize(int64) Option that, after upgrading the
connection, calls conn.SetReadLimit if a positive limit is configured.
The default behaviour (limit=0) is unchanged.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant