Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions core/src/main/java/com/alibaba/fastjson2/JSONReaderJSONB.java
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,7 @@ public String getString() {
if (strlen < 0) {
return symbolTable.getName(-strlen);
}
checkStrLen(strlen, strBegin, end);

Charset charset;
if (strtype == BC_STR_ASCII) {
Expand Down Expand Up @@ -604,6 +605,7 @@ public Object readAny() {
}
case BC_STR_UTF8: {
int strlen = readLength();
checkStrLenCopy(strlen, offset, end);

if (STRING_CREATOR_JDK11 != null && !JDKUtils.BIG_ENDIAN) {
if (valueBytes == null) {
Expand Down Expand Up @@ -634,12 +636,14 @@ public Object readAny() {
}
case BC_STR_UTF16: {
int strlen = readLength();
checkStrLenCopy(strlen, offset, end);
String str = new String(bytes, offset, strlen, StandardCharsets.UTF_16);
offset += strlen;
return str;
}
case BC_STR_UTF16LE: {
int strlen = readLength();
checkStrLenCopy(strlen, offset, end);

String str;
if (STRING_CREATOR_JDK11 != null && !JDKUtils.BIG_ENDIAN) {
Expand All @@ -655,6 +659,7 @@ public Object readAny() {
}
case BC_STR_UTF16BE: {
int strlen = readLength();
checkStrLenCopy(strlen, offset, end);

String str;
if (STRING_CREATOR_JDK11 != null && JDKUtils.BIG_ENDIAN) {
Expand All @@ -673,6 +678,7 @@ public Object readAny() {
GB18030 = Charset.forName("GB18030");
}
int strlen = readLength();
checkStrLenCopy(strlen, offset, end);
String str = new String(bytes, offset, strlen, GB18030);
offset += strlen;
return str;
Expand Down Expand Up @@ -959,6 +965,7 @@ public Object readAny() {
if (strlen < 0) {
return symbolTable.getName(-strlen);
}
checkStrLen(strlen, offset, end);

if (STRING_CREATOR_JDK8 != null) {
String str = latin1StringJDK8(bytes, offset, strlen);
Expand Down Expand Up @@ -2622,10 +2629,12 @@ public String readFieldName() {
Charset charset = null;
String str = null;
if (strtype == BC_STR_ASCII_FIX_MIN + 1) {
checkStrLen(1, offset, end);
str = TypeUtils.toString((char) (bytes[offset] & 0xff));
strlen = 1;
offset++;
} else if (strtype == BC_STR_ASCII_FIX_MIN + 2) {
checkStrLen(2, offset, end);
str = TypeUtils.toString(
(char) (bytes[offset] & 0xff),
(char) (bytes[offset + 1] & 0xff)
Expand All @@ -2638,10 +2647,13 @@ public String readFieldName() {
if (strtype == BC_STR_ASCII) {
strlen = readLength();
strBegin = offset;
checkStrLen(strlen, offset, end);
} else {
final int offset = this.offset;
strlen = strtype - BC_STR_ASCII_FIX_MIN;
Comment thread
wenshao marked this conversation as resolved.
Resolved
checkStrLen(strlen, offset, end);

// end may itself exceed bytes.length, so the array bound has to stay as well
if (offset + strlen > bytes.length) {
throw new JSONException("illegal jsonb data");
}
Expand Down Expand Up @@ -2785,6 +2797,7 @@ public String readFieldName() {
} else if (strtype == BC_STR_UTF8) {
strlen = readLength();
strBegin = offset;
checkStrLen(strlen, offset, end);

if (STRING_CREATOR_JDK11 != null && !JDKUtils.BIG_ENDIAN) {
if (valueBytes == null) {
Expand Down Expand Up @@ -2812,10 +2825,12 @@ public String readFieldName() {
} else if (strtype == BC_STR_UTF16) {
strlen = readLength();
strBegin = offset;
checkStrLen(strlen, offset, end);
charset = StandardCharsets.UTF_16;
} else if (strtype == BC_STR_UTF16LE) {
strlen = readLength();
strBegin = offset;
checkStrLen(strlen, offset, end);

if (STRING_CREATOR_JDK11 != null && !JDKUtils.BIG_ENDIAN) {
byte[] chars = new byte[strlen];
Expand All @@ -2828,6 +2843,7 @@ public String readFieldName() {
} else if (strtype == BC_STR_UTF16BE) {
strlen = readLength();
strBegin = offset;
checkStrLen(strlen, offset, end);

if (STRING_CREATOR_JDK11 != null && JDKUtils.BIG_ENDIAN) {
byte[] chars = new byte[strlen];
Expand All @@ -2839,6 +2855,7 @@ public String readFieldName() {
charset = StandardCharsets.UTF_16BE;
} else if (strtype == BC_STR_GB18030) {
strlen = readLength();
checkStrLen(strlen, offset, end);

if (GB18030 == null) {
GB18030 = Charset.forName("GB18030");
Expand Down Expand Up @@ -2911,6 +2928,7 @@ public String readString() {

String str = null;
if (strlen >= 0) {
checkStrLen(strlen, offset, end);
if (STRING_CREATOR_JDK11 != null) {
byte[] chars = new byte[strlen];
System.arraycopy(bytes, offset, chars, 0, strlen);
Expand Down Expand Up @@ -2977,6 +2995,7 @@ private String readString(Charset charset) {
if (strlen < 0) {
return symbolTable.getName(-strlen);
}
checkStrLen(strlen, offset, end);

char[] chars = null;
if (JVM_VERSION == 8 && strtype == BC_STR_UTF8 && strlen < 8192) {
Expand Down Expand Up @@ -3012,6 +3031,7 @@ private String readString(Charset charset) {
private void readGB18030() {
strlen = readLength();
strBegin = offset;
checkStrLenCopy(strlen, offset, end);

if (GB18030 == null) {
GB18030 = Charset.forName("GB18030");
Expand All @@ -3021,6 +3041,7 @@ private void readGB18030() {
private String readUTF16BE() {
strlen = readLength();
strBegin = offset;
checkStrLenCopy(strlen, offset, end);

if (STRING_CREATOR_JDK11 != null && JDKUtils.BIG_ENDIAN) {
byte[] chars = new byte[strlen];
Expand Down Expand Up @@ -3054,6 +3075,7 @@ private String readUTF16LE() {
strlen = readLength();
}
strBegin = offset;
checkStrLenCopy(strlen, offset, end);

if (strlen == 0) {
return "";
Expand Down Expand Up @@ -3089,6 +3111,7 @@ private String readStringUTF8() {
strlen = readLength();
}
strBegin = offset;
checkStrLenCopy(strlen, offset, end);

if (STRING_CREATOR_JDK11 != null && !JDKUtils.BIG_ENDIAN) {
if (valueBytes == null) {
Expand Down Expand Up @@ -6256,6 +6279,35 @@ static void checkBigintLen(int len, int offset, int end) {
}
}

/**
* Bound a string byte length against the bytes left in the frame. A negative length is a symbol
* reference only at the sites that resolve one before calling - {@link #getString()},
* {@link #readAny()}'s BC_STR_ASCII branch, {@link #readString()}, {@link #readString(Charset)}
* and {@link #readFieldName()}, which resolves it after its guards - so those pass it through.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Critical] R2-1: [fails-closed] The checkStrLen pass-through contract is not delivered inside readFieldName() — a hostile negative wire length still escapes JSONB.parseObject as a raw RuntimeException instead of JSONException, the exact outcome the description says this class of guard eliminates. At the BC_STR_ASCII arm, the shared name-cache gate bytes[offset + strlen - 1] > 0 evaluates the array read before nameValue0 != -1, so a negative length from readLength() (0xF0 = -16) indexes bytes[-15] and throws ArrayIndexOutOfBoundsException — on every JVM, no JDK-11/endianness precondition, reachable straight through parseObject(byte[], off, len, JSONObject.class). The UTF8/UTF16LE/UTF16BE arms' JDK11 fast paths consume the length before the tail (new byte[strlen] throws NegativeArraySizeException on JDK 11+ LE/BE; the UTF8 path rewinds the cursor via offset += strlen). And the tails the contract leans on are not safe on the default path either: symbolTable is null on the ofJSONB(byte[], int, int) readers that parseObject itself builds, so every negative reaching a "resolution" tail NPEs (:2867, :2996, :966, :160, plus :1960 which the javadoc does not list). The new test's exclusion comments (:155, :179) describe that NPE path as a symbol resolution. The over-length half of the contract is genuinely closed at these arms — the residual is precisely the negative half.

Witness (probe on this PR's build; base = parent blob, arms discriminated):

parseObject [BC_OBJECT][UTF16LE][-16] frameLen=5 -> THROWN java.lang.NegativeArraySizeException: -16
readFieldName [BC_STR_ASCII][0xF0] -> THROWN java.lang.ArrayIndexOutOfBoundsException: Index -15 (via parseObject: Index -14)
parseObject(frame(BC_STR_UTF16, -16), String.class) -> THROWN NullPointerException "this.symbolTable" is null @ :2996
control: same negative frame + real SymbolTable -> parses "name22", no exception (NPE is the null default-path table)
positive control: over-length 40 -> JSONException string length out of range: 40, available: 2
base arm: identical crashes at the merge base (pre-existing; this files the contract gap, not a regression)
one-term strlen >= 0 gate probe: AIOOBE gone, but the arm then NPEs at the tail on the default path

Suggested fix — fail the negative closed while keeping the ordinal path where a table exists:

// ASCII arm's shared cache gate (:2741-2742)
if (strlen >= 0 && bytes[offset + strlen - 1] > 0 && nameValue0 != -1) {
// UTF16LE (:2835) / UTF16BE (:2848) / UTF8 (:2802) fast paths
if (strlen >= 0 && STRING_CREATOR_JDK11 != null && !JDKUtils.BIG_ENDIAN) {
// then fail the negative closed at these arms (throw strLenOutOfRange(strlen, end - offset))
// or null-guard the tail resolution — the gates alone still NPE via parseObject

The fix must not remove the ordinal semantics: a negative ASCII/UTF8 name length is a legitimate symbol reference by wire design (BC_INT32_NUM_MIN = -16; the tail resolves strlen < 0 at :2862–2868 and readFieldNameHashCode at :1493), so reject only where resolution is unavailable — and the strict-> over-length bound plus the fixed arm's array bound (:2654–2656, kept because ofJSONB does not validate off + length <= bytes.length) must stay. Please add fieldNameNegativeLengthRejected / fieldNameNegativeAsciiLength to JSONBStringLengthTest — drive readFieldName() with BC_INT32_NUM_MIN lengths for the four string types and assert the frame-bound JSONException; they red today with NASE/AIOOBE/NPE and go red again if any added gate is removed.

— glm-5.3-flash via Qwen Code /review (v0.25.1)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed all three shapes on c71a11f and fixed them in 2b470c3, keeping the ordinal path wherever a table exists:

  • ASCII arm: reordered the cache gate to nameValue0 != -1 && bytes[offset + strlen - 1] > 0. nameValue0 is only set by the fixed-length arm, so a BC_STR_ASCII length never reaches the array read now, and the check is no more expensive than before.
  • UTF8 / UTF16LE / UTF16BE fast paths: gated on strlen >= 0, so a negative falls through to the symbol tail instead of hitting new byte[strlen] or rewinding the cursor.
  • Null table: the tails now go through a small symbolName(strlen) helper that throws strLenOutOfRange when symbolTable is null, used at getString, readAny's ASCII branch, readString(Charset) and readFieldName. readValueHashCode (:1960) gets the same treatment via symbolHashCode. readFieldNameHashCode and readTypeHashCode0 are unchanged.

The over-length bound and the fixed arm's array bound stay as they were. The checkStrLen javadoc now says the pass-through sites reject the negative when there is no table.

Tests: fieldNameNegativeLengthRejected drives readFieldName() with BC_INT32_NUM_MIN for all six string types, fieldNameNegativeAsciiLength goes through parseObject(..., JSONObject.class), and symbolLengthWithoutTableRejected covers the parseObject(String.class) / readAny / readValueHashCode NPE tails. Each asserts string length out of range: -16, available: 2. fieldNameSymbolLengthResolves is the positive control: the same negative ASCII name with a real SymbolTable still resolves to id.

on c71a11f source         -> 3 red (AIOOBE x2, NPE)
revert gate reorder       -> fieldNameNegativeAsciiLength + fieldNameNegativeLengthRejected red (AIOOBE)
revert UTF8 gate          -> fieldNameNegativeLengthRejected red (available: 18, cursor rewound)
revert UTF16LE gate       -> fieldNameNegativeLengthRejected red (NegativeArraySizeException)

The UTF16BE gate only runs on a big-endian JVM, so it can't be made to fail here. mvn validate is clean and core is 8014/8014 on JDK 21.

中文

在 c71a11f 上复现了这三种情况,已在 2b470c3 中修复,存在 symbol table 时序号解析路径保持不变:

  • ASCII 分支:缓存判断调整为 nameValue0 != -1 && bytes[offset + strlen - 1] > 0。nameValue0 只在定长分支中赋值,所以 BC_STR_ASCII 的负长度不会再走到数组访问,判断开销也没有增加。
  • UTF8 / UTF16LE / UTF16BE 快速路径:加上 strlen >= 0 条件,负值直接落到 symbol 解析尾部,不再触发 new byte[strlen] 或回退游标。
  • symbolTable 为 null:尾部改为调用 symbolName(strlen),symbolTable 为 null 时抛出 strLenOutOfRange,用于 getString、readAny 的 ASCII 分支、readString(Charset) 和 readFieldName。readValueHashCode(:1960)通过 symbolHashCode 做同样处理。readFieldNameHashCode 和 readTypeHashCode0 未改动。

超长上界检查和定长分支的数组边界保持不变。checkStrLen 的 javadoc 已注明:没有 symbol table 时,这些调用点会拒绝负值。

测试:fieldNameNegativeLengthRejected 用 BC_INT32_NUM_MIN 对六种字符串类型直接调用 readFieldName();fieldNameNegativeAsciiLength 走 parseObject(..., JSONObject.class);symbolLengthWithoutTableRejected 覆盖 parseObject(String.class) / readAny / readValueHashCode 的 NPE 路径,均断言 string length out of range: -16, available: 2。fieldNameSymbolLengthResolves 为正向对照:同样的负长度 ASCII 名称在有 SymbolTable 时仍解析为 id。

逐项删除验证结果见上方代码块。UTF16BE 的条件只在大端 JVM 上执行,本机无法让其失败。mvn validate 无告警,core 在 JDK 21 上 8014/8014 通过。

* A site that copies the length straight out of the backing array must use
* {@link #checkStrLenCopy} instead, which rejects the negative too.
*/
static void checkStrLen(int strlen, int offset, int end) {
Comment thread
wenshao marked this conversation as resolved.
Resolved
if (strlen > end - offset) {
throw strLenOutOfRange(strlen, end - offset);
}
}

/**
* Bound a string byte length that is copied directly, with no symbol reference resolved ahead of
* it, so a negative wire length is rejected here rather than reaching the copy as a negative
* array size or count.
*/
static void checkStrLenCopy(int strlen, int offset, int end) {
if (strlen < 0 || strlen > end - offset) {
throw strLenOutOfRange(strlen, end - offset);
}
}

static JSONException strLenOutOfRange(int strlen, int available) {
return new JSONException("string length out of range: " + strlen + ", available: " + available);
}

static JSONException outOfBoundsCheckFromToIndex(int offset, int end) {
return new JSONException("offset overflow, offset " + offset + ", end " + end);
}
Expand Down
Loading
Loading