Repository navigation
fix: validate declared array length in JSONReaderJSONB.startArray() to prevent pre-allocation OOM (same class as #7669) - #7733
Conversation
The BC_ARRAY / BC_BINARY branches of JSONReaderJSONB.startArray() read the array length via readInt32Value() without any bound check, then callers pre-allocate arrays/collections (new long[]/int[]/String[]/ArrayList(len)) with that length. A small crafted JSONB payload can declare Integer.MAX_VALUE elements and trigger an immediate over-sized allocation (OutOfMemoryError / DoS). This mirrors the fix already applied to BC_BIGINT/BC_BINARY byte[] paths (checkBigintLen, alibaba#7696/alibaba#7705): a declared length larger than the remaining buffer is malformed, since each element occupies at least one byte. Related: alibaba#7669
wenshao
left a comment
There was a problem hiding this comment.
Reviewed — no blockers. Suggestions are inline.
中文说明
已审查——无阻断问题。 建议见行内评论。
— qwen3.8-max-preview via Qwen Code /review
| static void checkArrayLen(int len, int offset, int end) { | ||
| // Each array/collection element occupies at least one byte in the JSONB stream, | ||
| // so a declared length larger than the remaining buffer is malformed input. |
There was a problem hiding this comment.
[Suggestion] No regression test covers the new checkArrayLen validation. The prior fix for the same vulnerability class (#7669, fixed by #7696/#7705) shipped with tests for both excessive and negative lengths via crafted byte payloads; this fix for the analogous startArray() path has none. — Concrete cost: a future refactor of startArray() (e.g., inlining the length read or reordering branches) could silently remove the guard and re-expose the OOM/DoS vector (a 6-byte payload declaring Integer.MAX_VALUE elements triggers multi-gigabyte pre-allocation in callers like ObjectReaderImplList).
中文说明
新增的 checkArrayLen 校验没有配套的回归测试。同类漏洞的前次修复(#7669,由 #7696/#7705 修复)均附带了针对超大长度和负数长度的测试用例;本次对 startArray() 路径的修复没有。具体风险:未来对 startArray() 的重构(如内联长度读取或调整分支顺序)可能无意中移除该校验,导致 OOM/DoS 漏洞复现(仅 6 字节的 JSONB 载荷即可声明 Integer.MAX_VALUE 个元素,在 ObjectReaderImplList 等调用方触发数 GB 的预分配)。
— qwen3.8-max-preview via Qwen Code /review
| static void checkArrayLen(int len, int offset, int end) { | ||
| // Each array/collection element occupies at least one byte in the JSONB stream, | ||
| // so a declared length larger than the remaining buffer is malformed input. | ||
| // Guards against a small crafted payload declaring Integer.MAX_VALUE elements | ||
| // that triggers an immediate over-sized array pre-allocation (OOM / DoS). | ||
| if (len < 0 || len > end - offset) { |
There was a problem hiding this comment.
[Suggestion] checkArrayLen is structurally identical to the pre-existing checkBigintLen (line 6320) — same signature (int, int, int), same condition len < 0 || len > end - offset, same message template; only the label string differs. — Concrete cost: if the bounds-check semantics need revision (e.g., accounting for minimum element size > 1 byte), two structurally identical methods plus three inline copies (lines 698, 3724, 4498) must be found and updated independently. Consider unifying into a single parameterized helper, e.g. checkLength(int len, int offset, int end, String label).
中文说明
checkArrayLen 与已有的 checkBigintLen(第 6320 行)结构完全一致——签名相同 (int, int, int)、判断条件相同 len < 0 || len > end - offset、消息模板相同,仅标签字符串不同。具体成本:如果边界检查语义需要修改(例如考虑最小元素大小 > 1 字节的情况),需要独立定位并更新两个结构相同的方法以及三处内联副本(第 698、3724、4498 行)。建议统一为一个参数化的辅助方法,例如 checkLength(int len, int offset, int end, String label)。
— qwen3.8-max-preview via Qwen Code /review
| // Guards against a small crafted payload declaring Integer.MAX_VALUE elements | ||
| // that triggers an immediate over-sized array pre-allocation (OOM / DoS). | ||
| if (len < 0 || len > end - offset) { | ||
| throw new JSONException("array length out of range: " + len + ", available: " + (end - offset)); |
There was a problem hiding this comment.
[Suggestion] The error message omits the buffer offset where the malformed array header was found. The dominant convention in this class includes offset + "/" + bytes.length (10+ sites), which materially aids debugging of malformed payloads in nested structures. — Concrete cost: an oncall engineer hex-dumping a multi-KB payload sees "array length out of range: 2147483647, available: 42" but cannot tell where in the buffer the bad header sits without manual scanning.
| throw new JSONException("array length out of range: " + len + ", available: " + (end - offset)); | |
| throw new JSONException("array length out of range at offset " + offset + "/" + end + ": " + len + ", available: " + (end - offset)); |
中文说明
错误消息中缺少格式错误的数组头所在的缓冲区偏移量。本类中的主流约定包含 offset + "/" + bytes.length(10 余处),这对于调试嵌套结构中的畸形载荷非常有帮助。具体成本:值班工程师在 hex-dump 一个多 KB 载荷时,看到 "array length out of range: 2147483647, available: 42" 却无法判断错误头部在缓冲区中的位置,只能手动扫描。
— qwen3.8-max-preview via Qwen Code /review
…rich error msg - Add BC_ARRAY declared-length OOM/DoS regression tests to Issue7669 (same vulnerability class as alibaba#7669; covers int[]/long[]/String[] overflow and negative length, plus a valid-array smoke test) - Extract shared checkLength(len, offset, end, label) helper; checkArrayLen and checkBigintLen now delegate to it, removing duplicated bounds-check logic - Include buffer offset in the 'out of range' error message for easier debugging Relates to alibaba#7733, alibaba#7669
|
Thanks @wenshao — addressed all three points:
All tests pass locally. PTAL. |
wenshao
left a comment
There was a problem hiding this comment.
Reviewed — no blockers. Suggestions are inline.
中文说明
已审查——无阻断问题。 建议见行内评论。
— qwen3.8-max-preview via Qwen Code /review (v0.21.3)
| public void testArrayValidPayloadStillWorks() { | ||
| int[] value = {1, 2, 3}; | ||
| byte[] jsonbBytes = JSONB.toBytes(value); |
There was a problem hiding this comment.
[Suggestion] The valid-payload regression test uses a 3-element array, which JSONB encodes as BC_ARRAY_FIX (ARRAY_FIX_LEN = 15), so startArray() returns via the fix-array branch before checkArrayLen is reached. This test cannot detect an over-rejection bug in the new check. — Failure scenario: if checkLength were over-strict (e.g. len >= end - offset), every valid BC_ARRAY payload with >15 elements would fail to parse, yet this test stays green because {1, 2, 3} round-trips through the untouched fix-array path.
| public void testArrayValidPayloadStillWorks() { | |
| int[] value = {1, 2, 3}; | |
| byte[] jsonbBytes = JSONB.toBytes(value); | |
| public void testArrayValidPayloadStillWorks() { | |
| int[] value = new int[32]; | |
| for (int i = 0; i < value.length; i++) { | |
| value[i] = i; | |
| } | |
| byte[] jsonbBytes = JSONB.toBytes(value); |
中文说明
[Suggestion] 有效载荷回归测试使用了 3 个元素的数组,JSONB 会将其编码为 BC_ARRAY_FIX(ARRAY_FIX_LEN = 15),因此 startArray() 通过 fix-array 分支直接返回,不会执行 checkArrayLen。该测试无法检测新校验中的过度拒绝缺陷。 — 失败场景:如果 checkLength 过于严格(例如 len >= end - offset),所有超过 15 个元素的有效 BC_ARRAY 载荷都将解析失败,但此测试仍会通过,因为 {1, 2, 3} 走的是未经修改的 fix-array 路径。
建议使用超过 15 个元素的数组以强制 BC_ARRAY 编码,例如 int[] value = new int[32];。
— qwen3.8-max-preview via Qwen Code /review (v0.21.3)
| @Test | ||
| public void testArrayDeclaredLengthOOM_int() { | ||
| assertThrows(JSONException.class, () -> JSONB.parseObject(ARRAY_PAYLOAD_MAX_LEN, int[].class)); |
There was a problem hiding this comment.
[Suggestion] The BC_BINARY branch of startArray() (line 1437–1440) received the same checkArrayLen fix but has no test exercising it through startArray(). All new tests use 0xA4 (BC_ARRAY); the existing binary tests go through readBinary(), a different method with its own inline check. — Failure scenario: if a future refactor removes checkArrayLen from only the BC_BINARY branch, no test catches it. A crafted payload {0x91, 0x48, 0x7F, 0xFF, 0xFF, 0xFF} via JSONB.parseObject(payload, int[].class) would bypass validation and OOM.
| @Test | |
| public void testArrayDeclaredLengthOOM_int() { | |
| assertThrows(JSONException.class, () -> JSONB.parseObject(ARRAY_PAYLOAD_MAX_LEN, int[].class)); | |
| @Test | |
| public void testArrayDeclaredLengthOOM_int() { | |
| assertThrows(JSONException.class, () -> JSONB.parseObject(ARRAY_PAYLOAD_MAX_LEN, int[].class)); | |
| } | |
| @Test | |
| public void testArrayDeclaredLengthOOM_binaryBranch() { | |
| // 0x91 = BC_BINARY routed through startArray() via typed array deserialization | |
| assertThrows(JSONException.class, () -> JSONB.parseObject(BINARY_PAYLOAD_MAX_LEN, int[].class)); | |
| } |
中文说明
[Suggestion] startArray() 的 BC_BINARY 分支(第 1437–1440 行)同样添加了 checkArrayLen 校验,但没有测试通过 startArray() 路径验证它。所有新测试使用 0xA4(BC_ARRAY);现有的 binary 测试走的是 readBinary(),一个有自己内联校验的不同方法。 — 失败场景:如果未来重构仅移除了 BC_BINARY 分支中的 checkArrayLen,没有测试会发现。通过 JSONB.parseObject(payload, int[].class) 发送构造载荷 {0x91, 0x48, 0x7F, 0xFF, 0xFF, 0xFF} 将绕过校验并触发 OOM。
建议添加一个通过 startArray() 路由 BC_BINARY 载荷的测试。
— qwen3.8-max-preview via Qwen Code /review (v0.21.3)
…NARY branch test
- testArrayValidPayloadStillWorks now uses a 32-element array
(ARRAY_FIX_LEN = 15): smaller arrays are encoded as BC_ARRAY_FIX and
bypass startArray()'s checkLength, so the previous 3-element test could
not catch an over-rejection bug in the new check. 32 elements force
BC_ARRAY encoding and actually exercise the guarded path.
- Add testArrayDeclaredLengthOOM_binaryBranch: crafted
{0x91 (BC_BINARY), 0x48, 0x7FFFFFFF} payload routed through startArray()
via typed array deserialization must be rejected by checkLength.
16/16 tests pass locally. Relates to alibaba#7733, alibaba#7669
|
Thanks @wenshao — round 2 addressed:
16/16 tests pass locally. PTAL. |
wenshao
left a comment
There was a problem hiding this comment.
Reviewed. Suggestions are inline.
中文说明
已审查。 建议见行内评论。
— qwen3.8-max via Qwen Code /review (v0.21.4)
| if (type != BC_ARRAY) { | ||
| throw new JSONException("array not support input " + error(type)); | ||
| } | ||
|
|
||
| return readInt32Value(); | ||
| int len = readInt32Value(); | ||
| checkArrayLen(len, offset, end); | ||
| return len; |
There was a problem hiding this comment.
[Suggestion] The same declared-length pre-allocation OOM class this PR closes in startArray() remains reachable through the untyped/nested BC_ARRAY decode paths that never call startArray(): readAny()'s default branch (~924), readObject()'s map-value branch (~392), and readArray()'s element branch (~1094). They read the length via readLength() (only bound: the 256M cap) and pre-allocate new JSONArray(len) / new ArrayList(len) with no remaining-buffer check. — Failure scenario: probe-verified against this PR's compiled code: JSONB.parse of the 6-byte payload {A4 48 0F FF FF FF} (declaring 268,435,455 elements) throws OutOfMemoryError under -Xmx300m — a ~1 GiB Object[] allocation from 6 bytes of input; the nested payload {A4 48 00 00 00 01 A4 48 0F FF FF FF}, the map-value variant, and parseObject(bytes, Object.class) all reproduce it. Typed paths and JSONB.parseArray are correctly rejected by this PR's new guard. All three sites are pre-existing code this diff does not touch and does not make newly reachable — suggesting as a follow-up in the same incremental series as the prior sibling fixes (PR 7696 / PR 7705), not a blocker of this PR.
Suggested follow-up (multiple sites):
// after each `len = readLength()` in the three inline BC_ARRAY branches
checkLength(len, offset, end, "array length");or fold the remaining-buffer check into readLength() itself so every declared-length consumer is covered at one site.
中文说明
本 PR 在 startArray() 中修复的“声明长度→预分配 OOM”同类问题,在从不调用 startArray() 的非类型化/嵌套 BC_ARRAY 解码路径上仍然可达:readAny() 的 default 分支(约 924 行)、readObject() 的 map-value 分支(约 392 行)、readArray() 的元素分支(约 1094 行)。它们通过 readLength() 读取长度(唯一约束是 256M 上限),随后直接 new JSONArray(len) / new ArrayList(len) 预分配,没有剩余缓冲区校验。 — 失败场景(已对本 PR 编译产物实测):JSONB.parse 一个 6 字节载荷 {A4 48 0F FF FF FF}(声明 268,435,455 个元素)在 -Xmx300m 下抛出 OutOfMemoryError —— 6 字节输入换约 1 GiB 的 Object[] 分配;嵌套载荷、map-value 变体与 parseObject(bytes, Object.class) 均可复现。类型化路径与 JSONB.parseArray 已被本 PR 的新校验正确拦截。这三处均为本 diff 未修改、也未新增可达性的既有代码——故作为后续跟进建议(与此前同类增量修复 PR 7696 / PR 7705 同一系列),不构成本 PR 的阻断项。
— qwen3.8-max via Qwen Code /review (v0.21.4)
| @Test | ||
| public void testArrayDeclaredLengthOOM_int() { | ||
| assertThrows(JSONException.class, () -> JSONB.parseObject(ARRAY_PAYLOAD_MAX_LEN, int[].class)); | ||
| } |
There was a problem hiding this comment.
[Suggestion] Every rejection payload places the declared-length field at the very end of the buffer, so end - offset evaluates to 0 in all rejection cases — the position-relative property of the check is never pinned. The one-line mutation len > end - offset → len > end was built and run against these tests: it survives all six green. — Failure scenario: if a future refactor degrades the remaining-bytes arithmetic to an absolute bound, a malformed array nested inside an outer container (offset > 0, declared length between end - offset and end) slips past the guard and the reader later dies with ArrayIndexOutOfBoundsException instead of JSONException. Discriminating input verified by probe: payload {95 A4 48 00 00 00 05 F0} via parseObject(bytes, int[][].class) (fix-array outer 0x95 wrapping an inner BC_ARRAY declaring 5 elements with 1 byte remaining) — this PR's build throws JSONException: array length out of range at offset 7/8: 5, available: 1; the mutant allocates int[5], overruns, and throws AIOOBE, while every test added here stays green.
Suggested fix — one added rejection test where the malformed BC_ARRAY is not at the buffer end:
static final byte[] NESTED_ARRAY_BAD_LEN = {
(byte) 0x95, // BC_ARRAY_FIX, 1 element
(byte) 0xA4, // inner BC_ARRAY
(byte) 0x48, // BC_INT32 length
0x00, 0x00, 0x00, 0x05, // declares 5 elements, only 1 byte remains
(byte) 0xF0
};
@Test
public void testArrayDeclaredLengthNotAtBufferEnd() {
assertThrows(JSONException.class,
() -> JSONB.parseObject(NESTED_ARRAY_BAD_LEN, int[][].class));
}中文说明
所有拒绝类测试载荷都把声明长度字段放在缓冲区末尾,因此所有拒绝场景下 end - offset 都等于 0 —— 校验的“相对当前位置”属性从未被测试钉住。单行变异 len > end - offset → len > end 已实际构建并运行:六个新测试全部仍然通过。 — 失败场景:如果未来重构把剩余字节数计算退化为绝对上界,嵌套在外层容器中的畸形数组(offset > 0,声明长度介于 end - offset 与 end 之间)将绕过校验,读取器随后以 ArrayIndexOutOfBoundsException 而非 JSONException 终止。已实测的区分性输入:载荷 {95 A4 48 00 00 00 05 F0} 经 parseObject(bytes, int[][].class) 解析(外层 fix-array 0x95 包裹一个声明 5 个元素但仅剩 1 字节的内层 BC_ARRAY)——本 PR 构建抛出 JSONException: array length out of range at offset 7/8: 5, available: 1;变异体则分配 int[5]、越界并抛出 AIOOBE,而此处新增的所有测试依然全绿。
建议修复:新增一个畸形 BC_ARRAY 不在缓冲区末尾的拒绝测试(代码见英文部分)。
— qwen3.8-max via Qwen Code /review (v0.21.4)
…AY not at buffer end Pin the position-relative bound (len > end - offset) enforced by startArray()'s checkLength, not an absolute bound. A malformed BC_ARRAY nested inside an outer container (offset > 0) would otherwise slip past the guard if a future refactor degenerates the remaining-bytes arithmetic to 'len > end', dying later with ArrayIndexOutOfBoundsException instead of JSONException. Payload: 0x95 (BC_ARRAY_FIX, 1 elem) wraps inner BC_ARRAY (0xA4) declaring 5 elements with only 1 byte (0xF0) remaining. Verified the current build throws JSONException: array length out of range at offset 7/8: 5, available: 1. Addresses reviewer suggestion R2-2 (review-4842883034).
|
@wenshao Both suggestions from review-4842883034 are now addressed. R2-2 (test hardening, in this PR #7733): Added R1 (separate follow-up PR): The three inline BC_ARRAY decode sites that bypass startArray() — readObject() map-value (~392), readAny() value (~927), readArray() element (~1099) — had the same unguarded All R2-1 + R2-2 regression tests pass (20/20, 0 Checkstyle violations). Still awaiting your final human APPROVED before merge — thanks! |
… OOM (R2-1) Folds the same checkLength remaining-buffer guard used by startArray() (PR #7733) into the three inline BC_ARRAY decode sites that never call startArray() and therefore pre-allocated new JSONArray(len)/new ArrayList(len) with no remaining-buffer check: - readObject() map-value branch (~392) - readAny() value branch (~927) - readArray() element branch (~1099) A 6-byte BC_ARRAY payload declaring ~268M elements against a tiny buffer (e.g. {A4 48 0F FF FF FF}) previously pre-allocated a ~1GiB Object[] and OOM'd; it now throws JSONException: array length out of range. Add regression tests covering all three paths (Issue7669): testUntypedArrayDeclaredLengthOOM_readAny (JSONB.parse -> readAny) testUntypedArrayDeclaredLengthOOM_readObject (JSONB.parseObject -> readObject) testUntypedArrayDeclaredLengthOOM_readArray (JSONB.parseArray -> readArray) Follow-up to PR #7733, same 7669 series (7696/7705/7733).
Harden inline readLength() array decode sites against declared-length OOM (follow-up to #7733)
背景
本 PR 修复的是与 #7669 完全同一类的问题(该 issue 由 #7696 / #7705 针对
BC_BIGINT/BC_BINARY修复):从不可信 JSONB 读到的"声明长度"在任何边界校验之前就被用于预分配。#7669 的修复只覆盖了byte[]分配路径(readBigInteger/readBinary),但数组容量路径startArray()至今未修。根因
JSONReaderJSONB.startArray()的BC_ARRAY(及BC_BINARY)分支直接return readInt32Value();:readInt32Value()不带 #7705 引入的缓冲区边界校验。三个数组读取入口全部经由它:readInt32ValueArray()→new int[entryCnt]readInt64ValueArray()→new long[entryCnt]readStringArray()→new String[entryCnt]因此一个仅 6 字节的 JSONB 载荷(
BC_ARRAY+BC_INT32+0x7FFFFFFF)即可让entryCnt = Integer.MAX_VALUE,在读取任何元素之前触发即时OutOfMemoryError(拒绝服务)。复现(防御性 PoC,不含武器化)
在 2.0.62 与 2.0.63(= 当前 master / 2.0.64-SNAPSHOT)下,
int[] / long[] / String[]均在-Xmx256m下即时 OOM;合法数组(如 len=2)行为不变。修复
把 #7705 用于
BC_BIGINT/BC_BINARY的同款校验len < 0 || len > end - offset应用到startArray():不影响合法输入:JSONB 中每个数组元素至少占 1 字节,故合法
entryCnt永远不会超过剩余缓冲区字节数;该下界与 #7705 的判定逻辑完全一致。关联
startArray)。CWE-789 (Memory Allocation with Excessive Size Value) / CWE-20 (Improper Input Validation)