Micronaut WebSocket server leaks native memory when a MessageBodyReader fails to decode a message
Description
Impact
Missing release of memory after effective lifetime (CWE-401). Each WebSocket message that a MessageBodyReader fails to decode leaves one Netty buffer retained. The memory is direct (native), outside the Java heap, so garbage collection does not reclaim it. A client that keeps sending malformed messages can exhaust direct memory and make the server fail.
AbstractNettyWebSocketHandler decodes a message for an @OnMessage parameter in three steps: type conversion, then a MediaTypeCodec for the @Consumes type, then a MessageBodyReader. For the reader it retains the frame content (wrap(msg.content().retain())) and calls MessageBodyReader.read(..., ByteBuffer). The default implementation of that method, and JsonMessageHandler.read, release the buffer only after a successful read. When the reader throws (for example a CodecException on malformed input), nobody releases it.
Preconditions, which make exploitation depend on the application:
- The endpoint's message parameter must reach the reader step. Plain JSON goes through the registered
JsonMediaTypeCodecfirst, andtext/plainthroughTextPlainCodec; those paths do not retain the buffer and do not leak. The leak needs an@OnMessagePOJO (or other non-convertible) parameter whose@Consumesmedia type has noMediaTypeCodecbut has aMessageBodyReaderthat can throw. - The client must be able to open the WebSocket. No authentication is needed beyond whatever the endpoint itself requires.
Per message, up to @OnMessage(maxPayloadLength) (65536 bytes by default) is retained.
Affected: micronaut-http-netty 4.6.4 to 4.10.30 and 5.0.0 to 5.2.13. The reader step came in with micronaut-core#11121 (4.6.4).
Patches
Not yet released. The fix releases the payload when the reader fails, and leaves the release to the reader when it succeeds, so nothing is released twice. It is public in micronaut-core#13686, which also fixes the fallback decoders receiving only the final fragment of a fragmented message. Tests check that the buffer's reference count ends at zero after a failing reader, for a single frame and for a fragmented message.
Workarounds
- Register a
MediaTypeCodecfor the endpoint's@Consumestype, or take the message asString,byte[]or a type that conversion handles, and decode it in the handler. - Make custom
MessageBodyReaderimplementations release aReferenceCountedByteBufferin afinallyblock when they overrideread(..., ByteBuffer). - Lower
@OnMessage(maxPayloadLength)and close sessions that send messages which fail to decode.
References
- micronaut-core#13686 (fix, public)
- Related but different: GHSA-9c73-4fch-jrwv (memory growth from fragmented messages), GHSA-f953-rxvf-mcf2 (frame freed before
ByteBufhandlers run).