GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Fix frame desynchronization in the binary memcache decoder · Raghuvardhan-Reddy78/netty@d3e5d88

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • codec-memcache/src
    • main/java/io/netty/handler/codec/memcache/binary
      • AbstractBinaryMemcacheDecoder.java
    • test/java/io/netty/handler/codec/memcache/binary
      • BinaryMemcacheDecoderTest.java
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎codec-memcache/src/main/java/io/netty/handler/codec/memcache/binary/AbstractBinaryMemcacheDecoder.java‎

Copy file name to clipboardExpand all lines: codec-memcache/src/main/java/io/netty/handler/codec/memcache/binary/AbstractBinaryMemcacheDecoder.java
+37-4Lines changed: 37 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
import io.netty.buffer.ByteBuf;
2121
import io.netty.buffer.Unpooled;
2222
import io.netty.channel.ChannelHandlerContext;
23+
import io.netty.handler.codec.CorruptedFrameException;
2324
import io.netty.handler.codec.DecoderResult;
2425
import io.netty.handler.codec.memcache.AbstractMemcacheObjectDecoder;
2526
import io.netty.handler.codec.memcache.DefaultLastMemcacheContent;
@@ -76,14 +77,15 @@ protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) t
7677
resetDecoder();
7778

7879
currentMessage = decodeHeader(in);
80+
validateHeader(currentMessage);
7981
state = State.READ_EXTRAS;
8082
} catch (Exception e) {
8183
resetDecoder();
8284
out.add(invalidMessage(e));
8385
return;
8486
}
8587
case READ_EXTRAS: try {
86-
byte extrasLength = currentMessage.extrasLength();
88+
int extrasLength = currentMessage.extrasLength() & 0xFF;
8789
if (extrasLength > 0) {
8890
if (in.readableBytes() < extrasLength) {
8991
return;
@@ -99,7 +101,7 @@ protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) t
99101
return;
100102
}
101103
case READ_KEY: try {
102-
short keyLength = currentMessage.keyLength();
104+
int keyLength = currentMessage.keyLength() & 0xFFFF;
103105
if (keyLength > 0) {
104106
if (in.readableBytes() < keyLength) {
105107
return;
@@ -116,8 +118,8 @@ protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) t
116118
}
117119
case READ_CONTENT: try {
118120
int valueLength = currentMessage.totalBodyLength()
119-
- currentMessage.keyLength()
120-
- currentMessage.extrasLength();
121+
- (currentMessage.keyLength() & 0xFFFF)
122+
- (currentMessage.extrasLength() & 0xFF);
121123
int toRead = in.readableBytes();
122124
if (valueLength > 0) {
123125
if (toRead == 0) {
@@ -166,6 +168,37 @@ protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) t
166168
}
167169
}
168170

171+
/**
172+
* Validates the length fields of a decoded header against each other.
173+
* <p/>
174+
* A header that fails this check can not be framed, so decoding stops permanently rather than attempting to
175+
* resynchronize, see the class documentation.
176+
* <p/>
177+
* Note that {@code keyLength} and {@code extrasLength} are unsigned in the protocol and are interpreted as such
178+
* here, see {@link BinaryMemcacheMessage#keyLength()} and {@link BinaryMemcacheMessage#extrasLength()}.
179+
*
180+
* @param header the decoded header to validate.
181+
* @throws CorruptedFrameException if the lengths in the header are inconsistent.
182+
*/
183+
private static void validateHeader(final BinaryMemcacheMessage header) {
184+
final int totalBodyLength = header.totalBodyLength();
185+
// The protocol defines totalBodyLength as an unsigned 32 bit value. A body that does not fit into a
186+
// positive int can not be represented, and is never legitimate.
187+
if (totalBodyLength < 0) {
188+
throw new CorruptedFrameException(
189+
"totalBodyLength must neither be negative nor be larger than " + Integer.MAX_VALUE + ", but was: "
190+
+ (totalBodyLength & 0xFFFFFFFFL));
191+
}
192+
// The protocol defines totalBodyLength as the "Length in bytes of extra + key + value", so the extras and
193+
// the key on their own can never be longer than the total body.
194+
final int extrasAndKeyLength = (header.extrasLength() & 0xFF) + (header.keyLength() & 0xFFFF);
195+
if (extrasAndKeyLength > totalBodyLength) {
196+
throw new CorruptedFrameException(
197+
"extrasLength + keyLength must not be larger than totalBodyLength, but was: "
198+
+ extrasAndKeyLength + " > " + totalBodyLength);
199+
}
200+
}
201+
169202
/**
170203
* Helper method to create a message indicating a invalid decoding result.
171204
*
Collapse file

‎codec-memcache/src/test/java/io/netty/handler/codec/memcache/binary/BinaryMemcacheDecoderTest.java‎

Copy file name to clipboardExpand all lines: codec-memcache/src/test/java/io/netty/handler/codec/memcache/binary/BinaryMemcacheDecoderTest.java
+218-2Lines changed: 218 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,15 +18,19 @@
1818
import io.netty.buffer.ByteBuf;
1919
import io.netty.buffer.Unpooled;
2020
import io.netty.channel.embedded.EmbeddedChannel;
21+
import io.netty.handler.codec.CorruptedFrameException;
2122
import io.netty.handler.codec.memcache.LastMemcacheContent;
2223
import io.netty.handler.codec.memcache.MemcacheContent;
2324
import io.netty.util.CharsetUtil;
2425
import io.netty.util.ReferenceCounted;
2526
import org.junit.jupiter.api.AfterEach;
2627
import org.junit.jupiter.api.BeforeEach;
2728
import org.junit.jupiter.api.Test;
29+
import org.junit.jupiter.params.ParameterizedTest;
30+
import org.junit.jupiter.params.provider.ValueSource;
2831

2932
import static org.junit.jupiter.api.Assertions.assertEquals;
33+
import static org.junit.jupiter.api.Assertions.assertFalse;
3034
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
3135
import static org.junit.jupiter.api.Assertions.assertNotNull;
3236
import static org.junit.jupiter.api.Assertions.assertNull;
@@ -70,12 +74,12 @@ public class BinaryMemcacheDecoderTest {
7074
private EmbeddedChannel channel;
7175

7276
@BeforeEach
73-
public void setup() throws Exception {
77+
public void setup() {
7478
channel = new EmbeddedChannel(new BinaryMemcacheRequestDecoder());
7579
}
7680

7781
@AfterEach
78-
public void teardown() throws Exception {
82+
public void teardown() {
7983
channel.finishAndReleaseAll();
8084
}
8185

@@ -273,4 +277,216 @@ public void shouldRetainCurrentMessageWhenSendingItOut() {
273277
read.release();
274278
// tearDown will call "channel.finish()"
275279
}
280+
281+
/**
282+
* Builds a header, where {@code keyLength}, {@code extrasLength} and {@code totalBodyLength} are written as the
283+
* raw (unsigned) protocol values. Requests and responses share this layout and only differ in the magic byte
284+
* and in how the two bytes at offset 6 are interpreted.
285+
*/
286+
private static ByteBuf header(boolean request, int keyLength, int extrasLength, int totalBodyLength) {
287+
return Unpooled.buffer()
288+
.writeByte(request ? 0x80 : 0x81) // magic
289+
.writeByte(0x00) // opcode
290+
.writeShort(keyLength)
291+
.writeByte(extrasLength)
292+
.writeByte(0x00) // dataType
293+
.writeShort(0x0000) // reserved (request) / status (response)
294+
.writeInt(totalBodyLength)
295+
.writeInt(0x00000000) // opaque
296+
.writeLong(0L); // cas
297+
}
298+
299+
/**
300+
* A message with no key, no extras and a four byte value, used to verify whether the decoder is still in sync
301+
* with the stream after the message preceding it.
302+
*/
303+
private static ByteBuf followUpMessage(boolean request) {
304+
return header(request, 0, 0, 4).writeBytes(new byte[] { 'A', 'B', 'C', 'D' });
305+
}
306+
307+
private void resetChannel(boolean request) {
308+
channel = new EmbeddedChannel(request
309+
? new BinaryMemcacheRequestDecoder() : new BinaryMemcacheResponseDecoder());
310+
}
311+
312+
private void assertFollowUpMessageDecodedInSync() {
313+
BinaryMemcacheMessage message = channel.readInbound();
314+
assertNotNull(message);
315+
assertTrue(message.decoderResult().isSuccess());
316+
assertEquals(0, message.keyLength());
317+
assertEquals(0, message.extrasLength());
318+
assertEquals(4, message.totalBodyLength());
319+
message.release();
320+
321+
MemcacheContent content = channel.readInbound();
322+
assertInstanceOf(LastMemcacheContent.class, content);
323+
assertEquals("ABCD", content.content().toString(CharsetUtil.UTF_8));
324+
content.release();
325+
326+
assertNull(channel.readInbound());
327+
}
328+
329+
private void assertRejectedWithoutExposingBody() {
330+
BinaryMemcacheMessage message = channel.readInbound();
331+
assertNotNull(message);
332+
assertTrue(message.decoderResult().isFailure());
333+
assertInstanceOf(CorruptedFrameException.class, message.decoderResult().cause());
334+
// A rejected header must not hand any part of the stream to the application. Before the length fields were
335+
// validated, the key of such a message could contain the bytes of the message following it, including its
336+
// opaque, which correlates a response to the request that asked for it.
337+
assertEquals(0, message.key() == null ? 0 : message.key().readableBytes());
338+
assertEquals(0, message.extras() == null ? 0 : message.extras().readableBytes());
339+
message.release();
340+
}
341+
342+
/**
343+
* The {@code extrasLength} header field is an unsigned 8 bit value, so it has to be interpreted as such rather
344+
* than as a signed {@code byte}. Otherwise the extras of a message with a length of {@code 0x80} or above are
345+
* not consumed and the following message is silently read as part of this message's value.
346+
*/
347+
@ParameterizedTest(name = "request = {0}")
348+
@ValueSource(booleans = { false, true })
349+
public void shouldDecodeExtrasWithLengthAboveSignedByteRange(boolean request) {
350+
resetChannel(request);
351+
352+
ByteBuf frame = header(request, 0, 0x80, 128).writeBytes(new byte[128]);
353+
channel.writeInbound(Unpooled.buffer().writeBytes(frame).writeBytes(followUpMessage(request)));
354+
frame.release();
355+
356+
BinaryMemcacheMessage message = channel.readInbound();
357+
assertNotNull(message);
358+
assertTrue(message.decoderResult().isSuccess());
359+
assertNotNull(message.extras());
360+
assertEquals(128, message.extras().readableBytes());
361+
assertEquals(128, message.extrasLength() & 0xFF);
362+
assertEquals(128, message.totalBodyLength());
363+
message.release();
364+
365+
// The whole body is extras, so there is no value.
366+
assertInstanceOf(LastMemcacheContent.class, channel.readInbound());
367+
368+
assertFollowUpMessageDecodedInSync();
369+
}
370+
371+
/**
372+
* The {@code keyLength} header field is an unsigned 16 bit value, so it has to be interpreted as such rather
373+
* than as a signed {@code short}. Otherwise the key of a message with a length of {@code 0x8000} or above is
374+
* not consumed and the following message is silently read as part of this message's value.
375+
*/
376+
@ParameterizedTest(name = "request = {0}")
377+
@ValueSource(booleans = { false, true })
378+
public void shouldDecodeKeyWithLengthAboveSignedShortRange(boolean request) {
379+
resetChannel(request);
380+
381+
ByteBuf frame = header(request, 0x8000, 0, 32768).writeBytes(new byte[32768]);
382+
channel.writeInbound(Unpooled.buffer().writeBytes(frame).writeBytes(followUpMessage(request)));
383+
frame.release();
384+
385+
BinaryMemcacheMessage message = channel.readInbound();
386+
assertNotNull(message);
387+
assertTrue(message.decoderResult().isSuccess());
388+
assertNotNull(message.key());
389+
assertEquals(32768, message.key().readableBytes());
390+
assertEquals(32768, message.keyLength() & 0xFFFF);
391+
assertEquals(32768, message.totalBodyLength());
392+
message.release();
393+
394+
// The whole body is the key, so there is no value.
395+
assertInstanceOf(LastMemcacheContent.class, channel.readInbound());
396+
397+
assertFollowUpMessageDecodedInSync();
398+
}
399+
400+
/**
401+
* The protocol defines {@code totalBodyLength} as the length of extras + key + value, so a header where the
402+
* extras and the key alone are longer than the total body can not be framed and has to be rejected. Note that
403+
* this needs no oversized length at all: decoding a 20 byte key out of a 4 byte body reads past the end of the
404+
* message and desynchronizes the stream.
405+
*/
406+
@ParameterizedTest(name = "request = {0}")
407+
@ValueSource(booleans = { false, true })
408+
public void shouldRejectExtrasAndKeyLongerThanTotalBody(boolean request) {
409+
resetChannel(request);
410+
411+
ByteBuf frame = header(request, 20, 0, 4).writeBytes(new byte[] { 'w', 'x', 'y', 'z' });
412+
channel.writeInbound(Unpooled.buffer().writeBytes(frame).writeBytes(followUpMessage(request)));
413+
frame.release();
414+
415+
assertRejectedWithoutExposingBody();
416+
}
417+
418+
/**
419+
* {@code totalBodyLength} is an unsigned 32 bit value, so it can exceed what an {@code int} can represent. Such
420+
* a message has to be rejected rather than treated as having a negative body length, which would leave the body
421+
* on the wire to be decoded as the next header.
422+
*/
423+
@ParameterizedTest(name = "request = {0}")
424+
@ValueSource(booleans = { false, true })
425+
public void shouldRejectTotalBodyLengthAboveIntegerMaxValue(boolean request) {
426+
resetChannel(request);
427+
428+
ByteBuf frame = header(request, 0, 0, 0x80000000).writeBytes(new byte[] { 'w', 'x', 'y', 'z' });
429+
channel.writeInbound(Unpooled.buffer().writeBytes(frame).writeBytes(followUpMessage(request)));
430+
frame.release();
431+
432+
assertRejectedWithoutExposingBody();
433+
}
434+
435+
/**
436+
* A {@code totalBodyLength} close to {@link Integer#MAX_VALUE} is representable and has to be accepted, with
437+
* the value length derived from it staying positive. Subtracting a signed, negative {@code keyLength} from such
438+
* a total body length overflowed instead, so the value was treated as empty and the message was terminated
439+
* before its body had been read.
440+
*/
441+
@ParameterizedTest(name = "request = {0}")
442+
@ValueSource(booleans = { false, true })
443+
public void shouldNotOverflowValueLengthForLargeTotalBodyLength(boolean request) {
444+
resetChannel(request);
445+
446+
// 0x7FFFFFFF - (-32768) overflows, while 0x7FFFFFFF - 32768 does not. The body is far too large to supply,
447+
// so feed the key plus the first few value bytes and observe that the value is still being read.
448+
ByteBuf frame = header(request, 0x8000, 0, Integer.MAX_VALUE)
449+
.writeBytes(new byte[32768])
450+
.writeBytes(new byte[] { 'v', 'a', 'l', 'u', 'e' });
451+
channel.writeInbound(frame);
452+
453+
BinaryMemcacheMessage message = channel.readInbound();
454+
assertNotNull(message);
455+
assertTrue(message.decoderResult().isSuccess());
456+
assertNotNull(message.key());
457+
assertEquals(32768, message.key().readableBytes());
458+
message.release();
459+
460+
MemcacheContent content = channel.readInbound();
461+
assertNotNull(content);
462+
assertEquals("value", content.content().toString(CharsetUtil.UTF_8));
463+
// Not the last chunk: the vast majority of the value is still outstanding.
464+
assertFalse(content instanceof LastMemcacheContent);
465+
content.release();
466+
467+
assertNull(channel.readInbound());
468+
}
469+
470+
/**
471+
* A framing violation can not be recovered from, because there is no way to tell which of the length fields
472+
* lied. Decoding therefore has to stop permanently rather than attempt to resynchronize: everything that
473+
* arrives after the rejected header, including otherwise well formed messages, must be discarded.
474+
*/
475+
@ParameterizedTest(name = "request = {0}")
476+
@ValueSource(booleans = { false, true })
477+
public void shouldStopDecodingPermanentlyAfterRejectingAHeader(boolean request) {
478+
resetChannel(request);
479+
480+
ByteBuf frame = header(request, 20, 0, 4).writeBytes(new byte[] { 'w', 'x', 'y', 'z' });
481+
channel.writeInbound(frame);
482+
483+
assertRejectedWithoutExposingBody();
484+
assertNull(channel.readInbound());
485+
486+
// Several perfectly valid messages arriving afterwards, in separate reads, must all be dropped.
487+
for (int i = 0; i < 3; i++) {
488+
channel.writeInbound(followUpMessage(request));
489+
assertNull(channel.readInbound());
490+
}
491+
}
276492
}

0 commit comments

Comments
0 (0)
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.