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 — Strictly validate MQTT UTF-8 Encoded String (#16939) (#16965) · lltopk/netty@6b53da9

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • codec-mqtt/src
    • main/java/io/netty/handler/codec/mqtt
      • MqttDecoder.java
    • test/java/io/netty/handler/codec/mqtt
      • MqttCodecTest.java
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎codec-mqtt/src/main/java/io/netty/handler/codec/mqtt/MqttDecoder.java‎

Copy file name to clipboardExpand all lines: codec-mqtt/src/main/java/io/netty/handler/codec/mqtt/MqttDecoder.java
+81-7Lines changed: 81 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,10 @@
2727
import io.netty.util.Signal;
2828
import io.netty.util.internal.ObjectUtil;
2929

30+
import java.nio.ByteBuffer;
31+
import java.nio.charset.CharacterCodingException;
32+
import java.nio.charset.CharsetDecoder;
33+
import java.nio.charset.CodingErrorAction;
3034
import java.util.ArrayList;
3135
import java.util.List;
3236

@@ -67,19 +71,42 @@ enum DecoderState {
6771

6872
private final int maxBytesInMessage;
6973
private final int maxClientIdLength;
74+
private final boolean strictUtf8Validation;
75+
// Lazily-initialised UTF-8 decoder reused across calls in the same channel/decoder
76+
// instance. ReplayingDecoder is invoked from a single thread per channel, so a non
77+
// thread-safe CharsetDecoder is safe to cache here.
78+
private CharsetDecoder utf8Decoder;
7079

7180
public MqttDecoder() {
72-
this(DEFAULT_MAX_BYTES_IN_MESSAGE, DEFAULT_MAX_CLIENT_ID_LENGTH);
81+
this(DEFAULT_MAX_BYTES_IN_MESSAGE, DEFAULT_MAX_CLIENT_ID_LENGTH, true);
7382
}
7483

7584
public MqttDecoder(int maxBytesInMessage) {
76-
this(maxBytesInMessage, DEFAULT_MAX_CLIENT_ID_LENGTH);
85+
this(maxBytesInMessage, DEFAULT_MAX_CLIENT_ID_LENGTH, true);
7786
}
7887

7988
public MqttDecoder(int maxBytesInMessage, int maxClientIdLength) {
89+
this(maxBytesInMessage, maxClientIdLength, true);
90+
}
91+
92+
/**
93+
* Creates a new {@link MqttDecoder}.
94+
*
95+
* @param maxBytesInMessage the maximum number of bytes a decoded message may consume.
96+
* @param maxClientIdLength the maximum length of the Client Identifier (CONNECT payload).
97+
* @param strictUtf8Validation if {@code true} (default), every UTF-8 Encoded String is
98+
* validated according to MQTT 3.1.1 and MQTT 5.0
99+
* malformed UTF-8 sequences (including
100+
* surrogates and overlong forms) and an embedded U+0000 are
101+
* rejected as a Malformed Packet. If {@code false}, the legacy
102+
* behaviour is preserved, malformed bytes are silently replaced
103+
* with {@code U+FFFD} and U+0000 is accepted.
104+
*/
105+
public MqttDecoder(int maxBytesInMessage, int maxClientIdLength, boolean strictUtf8Validation) {
80106
super(DecoderState.READ_FIXED_HEADER);
81107
this.maxBytesInMessage = ObjectUtil.checkPositive(maxBytesInMessage, "maxBytesInMessage");
82108
this.maxClientIdLength = ObjectUtil.checkPositive(maxClientIdLength, "maxClientIdLength");
109+
this.strictUtf8Validation = strictUtf8Validation;
83110
}
84111

85112
@Override
@@ -652,24 +679,71 @@ private void validateNoBytesRemain(int numberOfBytesConsumed) {
652679
}
653680
}
654681

655-
private static Result<String> decodeString(ByteBuf buffer) {
682+
private Result<String> decodeString(ByteBuf buffer) {
656683
return decodeString(buffer, 0, Integer.MAX_VALUE);
657684
}
658685

659-
private static Result<String> decodeString(ByteBuf buffer, int minBytes, int maxBytes) {
686+
private Result<String> decodeString(ByteBuf buffer, int minBytes, int maxBytes) {
660687
int size = decodeMsbLsb(buffer);
661688
int numberOfBytesConsumed = 2;
662689
if (size < minBytes || size > maxBytes) {
663690
buffer.skipBytes(size);
664691
numberOfBytesConsumed += size;
665692
return new Result<String>(null, numberOfBytesConsumed);
666693
}
667-
String s = buffer.toString(buffer.readerIndex(), size, CharsetUtil.UTF_8);
668-
buffer.skipBytes(size);
694+
final String s;
695+
if (strictUtf8Validation) {
696+
s = readStrictUtf8(buffer, size);
697+
} else {
698+
s = buffer.toString(buffer.readerIndex(), size, CharsetUtil.UTF_8);
699+
buffer.skipBytes(size);
700+
}
669701
numberOfBytesConsumed += size;
670702
return new Result<String>(s, numberOfBytesConsumed);
671703
}
672704

705+
/**
706+
* Reads {@code length} bytes from {@code buffer} and decodes them as a strictly validated
707+
* UTF-8 Encoded String per MQTT 3.1.1 and MQTT 5.0.
708+
* Throws a {@link DecoderException} if the sequence is malformed or contains U+0000.
709+
*/
710+
private String readStrictUtf8(ByteBuf buffer, int length) {
711+
if (length == 0) {
712+
return "";
713+
}
714+
final int readerIndex = buffer.readerIndex();
715+
final ByteBuffer nioBuf;
716+
if (buffer.nioBufferCount() == 1) {
717+
nioBuf = buffer.nioBuffer(readerIndex, length);
718+
} else {
719+
// Composite/multi-component buffer: copy out to ensure a contiguous view for the
720+
// CharsetDecoder. Strict UTF-8 validation requires examining all bytes anyway.
721+
byte[] tmp = new byte[length];
722+
buffer.getBytes(readerIndex, tmp);
723+
nioBuf = ByteBuffer.wrap(tmp);
724+
}
725+
if (utf8Decoder == null) {
726+
utf8Decoder = CharsetUtil.UTF_8.newDecoder()
727+
.onMalformedInput(CodingErrorAction.REPORT)
728+
.onUnmappableCharacter(CodingErrorAction.REPORT);
729+
}
730+
utf8Decoder.reset();
731+
final String s;
732+
try {
733+
s = utf8Decoder.decode(nioBuf).toString();
734+
} catch (CharacterCodingException e) {
735+
buffer.skipBytes(length);
736+
throw new DecoderException("invalid UTF-8 string in MQTT packet", e);
737+
}
738+
buffer.skipBytes(length);
739+
// The UTF-8 Encoded String MUST NOT include an encoding
740+
// of the null character U+0000. If received, this is a Malformed Packet.
741+
if (s.indexOf('\u0000') >= 0) {
742+
throw new DecoderException("MQTT UTF-8 Encoded String must not contain U+0000");
743+
}
744+
return s;
745+
}
746+
673747
/**
674748
*
675749
* @return the decoded byte[], numberOfBytesConsumed = byte[].length + 2
@@ -745,7 +819,7 @@ private static final class Result<T> {
745819
}
746820
}
747821

748-
private static Result<MqttProperties> decodeProperties(ByteBuf buffer) {
822+
private Result<MqttProperties> decodeProperties(ByteBuf buffer) {
749823
final long propertiesLength = decodeVariableByteInteger(buffer);
750824
int totalPropertiesLength = unpackA(propertiesLength);
751825
int numberOfBytesConsumed = unpackB(propertiesLength);
Collapse file

‎codec-mqtt/src/test/java/io/netty/handler/codec/mqtt/MqttCodecTest.java‎

Copy file name to clipboardExpand all lines: codec-mqtt/src/test/java/io/netty/handler/codec/mqtt/MqttCodecTest.java
+148Lines changed: 148 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818

1919
import io.netty.buffer.ByteBuf;
2020
import io.netty.buffer.ByteBufAllocator;
21+
import io.netty.buffer.Unpooled;
2122
import io.netty.buffer.UnpooledByteBufAllocator;
2223
import io.netty.channel.Channel;
2324
import io.netty.channel.ChannelHandlerContext;
@@ -63,6 +64,7 @@
6364
import static org.junit.jupiter.api.Assertions.assertEquals;
6465
import static org.junit.jupiter.api.Assertions.assertFalse;
6566
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
67+
import static org.junit.jupiter.api.Assertions.assertNotNull;
6668
import static org.junit.jupiter.api.Assertions.assertNull;
6769
import static org.junit.jupiter.api.Assertions.assertThrows;
6870
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -1334,4 +1336,150 @@ private void validateReasonCodeAndPropertiesVariableHeader(MqttReasonCodeAndProp
13341336
final MqttProperties actualProps = actual.properties();
13351337
validateProperties(expectedProps, actualProps);
13361338
}
1339+
1340+
/**
1341+
* Builds a minimal MQTT 3.1.1 CONNECT packet whose ClientId field contains the supplied
1342+
* raw bytes (length prefix is computed automatically). Protocol = "MQTT", level = 4,
1343+
* clean-session flag set, keepalive 60.
1344+
*/
1345+
private static ByteBuf buildConnectWithClientIdBytes(byte[] clientIdBytes) {
1346+
ByteBuf buf = Unpooled.buffer();
1347+
// variable header (10 bytes) + ClientId field (2 + N bytes); test packets stay small,
1348+
// so a single-byte Remaining Length is sufficient.
1349+
int remainingLength = 10 + 2 + clientIdBytes.length;
1350+
buf.writeByte(0x10); // CONNECT
1351+
buf.writeByte(remainingLength);
1352+
// Variable header
1353+
buf.writeShort(4);
1354+
buf.writeBytes(new byte[] {'M', 'Q', 'T', 'T'});
1355+
buf.writeByte(0x04); // protocol level (MQTT 3.1.1)
1356+
buf.writeByte(0x02); // clean session
1357+
buf.writeShort(60); // keep alive
1358+
// Payload: ClientId
1359+
buf.writeShort(clientIdBytes.length);
1360+
buf.writeBytes(clientIdBytes);
1361+
return buf;
1362+
}
1363+
1364+
private static MqttMessage decodeUtf8TestPacket(MqttDecoder decoder, ByteBuf in) {
1365+
EmbeddedChannel channel = new EmbeddedChannel(decoder);
1366+
try {
1367+
channel.writeInbound(in);
1368+
return channel.readInbound();
1369+
} finally {
1370+
channel.finishAndReleaseAll();
1371+
}
1372+
}
1373+
1374+
private static void assertMalformedUtf8(MqttMessage msg) {
1375+
assertNotNull(msg);
1376+
assertTrue(msg.decoderResult().isFailure(), "expected decoder failure but got: " + msg);
1377+
assertInstanceOf(DecoderException.class, msg.decoderResult().cause());
1378+
}
1379+
1380+
@Test
1381+
public void invalidTwoByteUtf8SequenceIsRejectedByDefault() {
1382+
// 0xC3 must be followed by a 10xxxxxx continuation byte; 0x28 is not.
1383+
ByteBuf packet = buildConnectWithClientIdBytes(new byte[] {(byte) 0xC3, 0x28});
1384+
assertMalformedUtf8(decodeUtf8TestPacket(new MqttDecoder(), packet));
1385+
}
1386+
1387+
@Test
1388+
public void truncatedMultibyteUtf8SequenceIsRejected() {
1389+
// Lone 0xC3 with no continuation byte at all (string ends mid-sequence).
1390+
ByteBuf packet = buildConnectWithClientIdBytes(new byte[] {(byte) 0xC3});
1391+
assertMalformedUtf8(decodeUtf8TestPacket(new MqttDecoder(), packet));
1392+
}
1393+
1394+
@Test
1395+
public void overlongNullUtf8EncodingIsRejected() {
1396+
// 0xC0 0x80 is the (invalid) Modified-UTF-8 overlong encoding of U+0000.
1397+
ByteBuf packet = buildConnectWithClientIdBytes(new byte[] {(byte) 0xC0, (byte) 0x80});
1398+
assertMalformedUtf8(decodeUtf8TestPacket(new MqttDecoder(), packet));
1399+
}
1400+
1401+
@Test
1402+
public void isolatedHighSurrogateUtf8IsRejected() {
1403+
// 0xED 0xA0 0x80 = U+D800, an unpaired UTF-16 high surrogate; not valid UTF-8.
1404+
ByteBuf packet = buildConnectWithClientIdBytes(new byte[] {(byte) 0xED, (byte) 0xA0, (byte) 0x80});
1405+
assertMalformedUtf8(decodeUtf8TestPacket(new MqttDecoder(), packet));
1406+
}
1407+
1408+
@Test
1409+
public void fiveByteOverlongUtf8SequenceIsRejected() {
1410+
// 0xF8 starts a 5-byte sequence which is not allowed by RFC 3629.
1411+
ByteBuf packet = buildConnectWithClientIdBytes(
1412+
new byte[] {(byte) 0xF8, (byte) 0x88, (byte) 0x80, (byte) 0x80, (byte) 0x80});
1413+
assertMalformedUtf8(decodeUtf8TestPacket(new MqttDecoder(), packet));
1414+
}
1415+
1416+
@Test
1417+
public void embeddedNullCharacterInUtf8StringIsRejected() {
1418+
// U+0000 must cause Malformed Packet.
1419+
ByteBuf packet = buildConnectWithClientIdBytes(new byte[] {'a', 0x00, 'b'});
1420+
assertMalformedUtf8(decodeUtf8TestPacket(new MqttDecoder(), packet));
1421+
}
1422+
1423+
@Test
1424+
public void wellFormedMultibyteUtf8IsAccepted() {
1425+
byte[] cid = {'h', 'e', 'l', 'l', 'o'};
1426+
ByteBuf packet = buildConnectWithClientIdBytes(cid);
1427+
MqttMessage msg = decodeUtf8TestPacket(new MqttDecoder(), packet);
1428+
assertNotNull(msg);
1429+
try {
1430+
assertTrue(msg.decoderResult().isSuccess(),
1431+
"expected success but got: " + msg.decoderResult().cause());
1432+
assertInstanceOf(MqttConnectMessage.class, msg);
1433+
assertEquals("hello", ((MqttConnectMessage) msg).payload().clientIdentifier());
1434+
} finally {
1435+
ReferenceCountUtil.release(msg);
1436+
}
1437+
}
1438+
1439+
@Test
1440+
public void emptyClientIdIsAcceptedUnderStrictUtf8() {
1441+
ByteBuf packet = buildConnectWithClientIdBytes(new byte[0]);
1442+
MqttMessage msg = decodeUtf8TestPacket(new MqttDecoder(), packet);
1443+
assertNotNull(msg);
1444+
try {
1445+
assertTrue(msg.decoderResult().isSuccess());
1446+
} finally {
1447+
ReferenceCountUtil.release(msg);
1448+
}
1449+
}
1450+
1451+
@Test
1452+
public void legacyModeAcceptsMalformedUtf8AsReplacementChar() {
1453+
ByteBuf packet = buildConnectWithClientIdBytes(new byte[] {(byte) 0xC3, 0x28});
1454+
MqttDecoder lenient = new MqttDecoder(8 * 1024 * 1024, 23, false);
1455+
MqttMessage msg = decodeUtf8TestPacket(lenient, packet);
1456+
assertNotNull(msg);
1457+
try {
1458+
assertTrue(msg.decoderResult().isSuccess(),
1459+
"lenient mode should accept malformed UTF-8");
1460+
assertInstanceOf(MqttConnectMessage.class, msg);
1461+
String cid = ((MqttConnectMessage) msg).payload().clientIdentifier();
1462+
assertNotNull(cid);
1463+
// java.lang.String inserts U+FFFD for malformed input. Exact length is JDK
1464+
// implementation defined; just make sure decoding did not throw.
1465+
assertTrue(cid.indexOf('\uFFFD') >= 0 || cid.length() > 0,
1466+
"expected replacement char or non-empty result");
1467+
} finally {
1468+
ReferenceCountUtil.release(msg);
1469+
}
1470+
}
1471+
1472+
@Test
1473+
public void legacyModeAcceptsEmbeddedNullCharacter() {
1474+
ByteBuf packet = buildConnectWithClientIdBytes(new byte[] {'a', 0x00, 'b'});
1475+
MqttDecoder lenient = new MqttDecoder(8 * 1024 * 1024, 23, false);
1476+
MqttMessage msg = decodeUtf8TestPacket(lenient, packet);
1477+
assertNotNull(msg);
1478+
try {
1479+
assertTrue(msg.decoderResult().isSuccess());
1480+
assertEquals("a\u0000b", ((MqttConnectMessage) msg).payload().clientIdentifier());
1481+
} finally {
1482+
ReferenceCountUtil.release(msg);
1483+
}
1484+
}
13371485
}

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.