Repository navigation
Harden inline readLength() array decode sites against declared-length OOM (follow-up to #7733) - #7776
Conversation
… OOM (R2-1) Folds the same checkLength remaining-buffer guard used by startArray() (PR alibaba#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 alibaba#7733, same 7669 series (7696/7705/7733).
wenshao
left a comment
There was a problem hiding this comment.
Reviewed. Suggestions are inline.
Not explored to full depth (tool budget reached): Change summary: PR #7776 is a security-hardening follow-u...: did not verify whether JSONB.toBytes(Map{"k"→int[32]}) wraps the array value in BC_TYPED_ANY (which would route testUntypedArrayDeclaredLengthOOM_readObject …; Change summary: PR #7776 is a security-hardening follow-u...: full core module test suite run against the committed tree (only Issue7669 was run; other pre-existing JSONB malformed-input tests were checked by grep for me…; Change summary: PR #7776 is a security-hardening follow-u...: per-site single-guard-removal experiments (the "passes without guards" evidence comes from the all-three-stripped state; I inferred per-site non-pinning from th…; Change summary: PR #7776 is a security-hardening follow-u...: dynamic tier ( -XX:+PrintInlining on a JSONB decode workload, JMH before/after) not run — the finding above is stated at the static/mechanism level only.; Change summary: PR #7776 is a security-hardening follow-u...: none — no check was left unfinished..
— qwen3.8-max via Qwen Code /review (v0.21.10)
| } | ||
|
|
||
| @Test | ||
| public void testUntypedArrayDeclaredLengthOOM_readObject() { |
There was a problem hiding this comment.
[Suggestion] This test never exercises the readObject() map-value BC_ARRAY guard (JSONReaderJSONB.java:407). JSONB.parseObject(bytes, Object.class) dispatches through readAny() (the Object.class shortcut), so the corrupted array is rejected by the readAny guard at line 932 — the same site the _readAny test already covers. A bytecode-verified deletion probe confirmed it: removing the line-407 guard leaves this test green, so the readObject() guard ships with zero regression coverage. — Failure scenario: a future refactor that drops the checkLength at line 407 revives the declared-length pre-allocation OOM (~1 GB new JSONArray from a 6-byte payload) on readObject()'s map-value path (reachable via the untyped JSONB.parseObject(bytes) overload) while this suite stays green.
Fix — route through readObject() via the untyped overload:
assertThrows(JSONException.class, () -> JSONB.parseObject(bytes));(keep the Object.class variant too if desired, and update the "readObject() takes the map-value BC_ARRAY branch" comment, which describes the opposite of what happens)
— qwen3.8-max via Qwen Code /review (v0.21.10)
| // JSONB.parse with no target type dispatches to readAny(); its BC_ARRAY | ||
| // branch reads the length via readLength() and pre-allocates | ||
| // new JSONArray(len) — now guarded by checkLength. | ||
| assertThrows(JSONException.class, () -> JSONB.parse(UNTYPED_ARRAY_MAX_LEN)); |
There was a problem hiding this comment.
[Suggestion] The type-only assertThrows(JSONException.class, ...) does not distinguish the new checkLength rejection from a later generic failure. Empirically reproduced: with the inline guards stripped, new JSONArray(0x0FFFFFFF) (~1 GB) still pre-allocates and a downstream JSONException (readAny overflow : 6/6 at JSONReaderJSONB.java:550) still satisfies this assertion — the test passes with the fix removed. — Failure scenario: on any CI heap large enough to absorb the ~1 GB attacker-controlled pre-allocation, a regression of this guard passes the suite silently (or surfaces as a flaky OOM on small-heap forks) — the fix rots while the tests claim to pin it.
Fix — pin the guard's own message, which no downstream failure produces (same change for the _readObject test; needs import static org.junit.jupiter.api.Assertions.assertTrue;):
JSONException ex = assertThrows(JSONException.class, () -> JSONB.parse(UNTYPED_ARRAY_MAX_LEN));
assertTrue(ex.getMessage().contains("array length out of range"));— qwen3.8-max via Qwen Code /review (v0.21.10)
| // `label` identifies the context in the error message (e.g. "array length", | ||
| // "BC_BIGINT length"). A declared length larger than the remaining buffer is | ||
| // malformed input and must be rejected before any pre-allocation. | ||
| static void checkLength(int len, int offset, int end, String label) { |
There was a problem hiding this comment.
[Suggestion] checkLength compiles to 76 bytes at the project's Java 8 source/target (measured: javac -source 8 -target 8 + javap; the pom pins maven.compiler.source/target=8 with no <release>), over double the 35-byte -XX:MaxInlineSize gate AGENTS.md asks hot-path methods to stay under, because the exception-message StringBuilder chain (~64 of the 76 bytes) lives in the same method as the two comparisons. It is called from five sites, three of them hot JSONB decode paths (readAny/readObject/readArray — once per decoded BC_ARRAY header). Note checkBigintLen shrank 52→10 bytes precisely by delegating. — Failure scenario: at 76 bytes, inlining relies on FreqInlineSize (325) plus per-site call-frequency profiling; in the interpreter and C1 tiers during warmup, and at any site whose profile stays cool, every array-length validation pays a real static call plus stack frame instead of ~9 bytes of inlined comparisons.
Fix — hot/cold split, leaving the guard at ~15–20 bytes:
static void checkLength(int len, int offset, int end, String label) {
if (len < 0 || len > end - offset) {
throwLengthOutOfRange(len, offset, end, label);
}
}
static void throwLengthOutOfRange(int len, int offset, int end, String label) {
throw new JSONException(
label + " out of range at offset " + offset + "/" + end + ": " + len + ", available: " + (end - offset));
}— qwen3.8-max via Qwen Code /review (v0.21.10)
| if (len < 0 || len > end - offset) { | ||
| throw new JSONException("BC_BIGINT length out of range: " + len + ", available: " + (end - offset)); | ||
| } | ||
| checkLength(len, offset, end, "BC_BIGINT length"); |
There was a problem hiding this comment.
[Suggestion] This PR folds checkBigintLen into the new shared checkLength (this line), but three pre-existing inline copies of the identical check for BC_BINARY lengths are left un-folded in the same file: readAny()'s BC_BINARY case (~line 700), readBinary() (~line 3739), and readBigInteger()'s BC_BINARY case (~line 4513). The messages have already drifted: "BC_BINARY length out of range: N" vs the new enriched "… out of range at offset O/E: N, available: A" format. Verified: at all three sites offset/end are evaluated after the length field is consumed, so checkLength(len, offset, end, "BC_BINARY length") is a drop-in whose only behavioural delta is the message enrichment. — Failure scenario: four implementations of the same security invariant now live in one file; the next hardening pass in this series must rediscover the three inline copies by hand to change the invariant or message consistently — miss one and malformed-length rejection behaves differently depending on which decode path saw it.
Fix — mirror this delegation at the three sites:
checkLength(len, offset, end, "BC_BINARY length");— qwen3.8-max via Qwen Code /review (v0.21.10)
| len = valueType - BC_ARRAY_FIX_MIN; | ||
| } | ||
|
|
||
| checkLength(len, offset, end, "array length"); |
There was a problem hiding this comment.
[Suggestion] The array-length guard is spelled two ways in this PR: the checkArrayLen wrapper (body exactly checkLength(len, offset, end, "array length") plus the 1-byte-per-element invariant comment) is used only at the two startArray() sites, while the three inline sites this PR adds (here, ~932 in readAny(), ~1105 in readArray()) bypass the wrapper and call checkLength directly with the identical label. startArray() measures 136 bytes at target 8 either way — the dual spelling buys no bytecode-size benefit. — Failure scenario: a future change to the array-length policy or message (e.g. an absolute cap like readLength()'s 256M limit) must find two spellings to stay consistent, and the invariant rationale comment is trapped in a wrapper three of the five array sites never route through — the same drift this PR exists to eliminate for checkBigintLen.
| checkLength(len, offset, end, "array length"); | |
| checkArrayLen(len, offset, end); |
(same change at the other two inline sites, ~932 and ~1105 — or delete the wrapper and keep five direct calls)
— qwen3.8-max via Qwen Code /review (v0.21.10)
…opies, hot/cold split, pin test messages
- R1-1: testUntypedArrayDeclaredLengthOOM_readObject now routes through the
untyped JSONB.parseObject(bytes) overload so it actually exercises the
readObject() map-value BC_ARRAY guard (line 407); the Object.class variant
short-circuited through readAny()
- R1-2: pin the guard's own message ("array length out of range") in the
untyped tests so a downstream generic JSONException cannot mask a removed guard
- R1-3: hot/cold split checkLength() — the two comparisons stay inlinable;
the message StringBuilder chain moved to throwLengthOutOfRange()
- R1-4: fold the three remaining inline BC_BINARY length checks
(readAny/readBinary/readBigInteger) into checkLength(..., "BC_BINARY length"),
unifying the message format
- R1-5: route all five array-length guard sites through checkArrayLen()
(startArray x2 + readObject/readAny/readArray) — single spelling
Issue7669: 20/20 pass. Full core suite: only pre-existing Chinese-path
resource failures (CSVTest2/CSVReaderTest4/Issue3559) remain, reproduced
on pristine d5155ee — unrelated to this PR.
|
Thanks @wenshao — round 1 addressed:
Tests: PTAL. |
wenshao
left a comment
There was a problem hiding this comment.
Partially reviewed — gaps disclosed.
Not explored to full depth (tool budget reached): "本次审查的 PR #7776 是 fastjson2 JSONB 解码的安全加固后续修复:为不经过…": none — all checks I started were completed. (Static bytecode measurement of startArray was deliberately skipped; the no-crossing conclusion rests on pre/post …; "本次审查的 PR #7776 是 fastjson2 JSONB 解码的安全加固后续修复:为不经过…": none** — all checks above completed within budget.; "本次审查的 PR #7776 是 fastjson2 JSONB 解码的安全加固后续修复:为不经过…": none — no check was left unfinished.; "本次审查的 PR #7776 是 fastjson2 JSONB 解码的安全加固后续修复:为不经过…": full reachability trace of readFieldNameHashCode / readTypeHashCode symbol-registration growth (HEAD 1625–1650, 2682+, 2945+) from a top-level JSONB.parse o…; "本次审查的 PR #7776 是 fastjson2 JSONB 解码的安全加固后续修复:为不经过…": none — no check was left unfinished at the budget ceiling., and 1 more.
Not reviewed: reverse audit — did not converge within the reverse-audit round cap of 5.
[Critical] skipValue() consumes stream-declared lengths with no remaining-buffer check — the exact defect class this PR hardens everywhere else in JSONReaderJSONB (JSONReaderJSONB.java:2512-2522 and 2590-2611; outside this diff's hunks, so this blocker rides the body). The BC_BINARY arm (2512-2514: int byteslen = readInt32Value(); offset += byteslen;), the BC_STR_ASCII/UTF8/UTF16 arms (2516-2522: int strlen = readInt32Value(); offset += strlen;), the BC_ARRAY arm (2590-2611: itemCnt = readInt32Value() unchecked), and the BC_OBJECT while(true) loop (no iteration counter) all advance offset by attacker-controlled lengths; readInt32Value() has no 256MB cap. — Failure scenario (probe-verified at this commit): (1) JSONB.parseObject(payload, Bean.class) where the unknown field's value is BC_BINARY declaring 0x7FFFFFFF bytes (payload A6 4A 6B 91 48 7F FF FF FF): offset += 0x7FFFFFFF int-wraps and the next field-name read throws raw ArrayIndexOutOfBoundsException: Index -2147483640 out of bounds for length 9 out of the public parse API instead of JSONException; (2) an unknown-field nested object whose string declares length −6 (payload A6 4A 6B A6 4A 78 79 48 FF FF FF FA): offset += -6 rewinds exactly onto the type byte and the BC_OBJECT while(true) loop re-dispatches the same 6 bytes forever — worker thread still RUNNABLE after 4 s; a 13-byte payload permanently pins a core, reproduced via both bean deserialization of unknown fields and JSONValidator.validate(); (3) BC_ARRAY arm: a net-zero-advance element (type 0x79 + BC_INT32 length 0xFFFFFFFA) spins 2,147,483,647 iterations (~2.5 s CPU) from a 12-19 byte payload, and the direct skipValue path throws AIOOBE instead of JSONException. Probe flipped: patching the arms with the same remaining-length check this PR introduces turns (1) into JSONException and (2) into clean rejection. Suggested fix: fold these arms into the shared guard this PR introduces — checkLength(byteslen, offset, end, "BC_BINARY length") and checkLength(strlen, offset, end, "string length") before the offset += at 2513/2521, checkArrayLen(itemCnt, offset, end) in the BC_ARRAY arm, plus the same shape in the element-skip loops' size == -1 inline arms and skipName() (~2639).
— qwen3.8-max via Qwen Code /review (v0.21.11)
| static void checkLength(int len, int offset, int end, String label) { | ||
| if (len < 0 || len > end - offset) { | ||
| throwLengthOutOfRange(len, offset, end, label); | ||
| } | ||
| } |
There was a problem hiding this comment.
[Suggestion] The declared-length pre-allocation OOM class this PR closes for BC_ARRAY/BC_BINARY/BC_BIGINT survives at the string decode sites: string lengths read via readLength() are never checked against end - offset before allocation — readAny()'s BC_STR_ASCII branch (~968), BC_STR_UTF8 (~608, new byte[strlen << 1]), BC_STR_UTF16LE/BE (~648/663), the JDK8 path via JDKUtils.latin1StringJDK8 (new char[strlen]), readString() (~2864-2920) and readFieldName() (~3113-3188). Failure scenario: probe-verified at this commit — JSONB.parse(new byte[]{0x79, 0x48, 0x0F, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF}) under -Xmx128m dies with OutOfMemoryError: Java heap space in ~95 ms: a 6-byte input declaring 268,435,455 string bytes (one under readLength()'s own 256 MB cap, which it passes) exhausts the heap; the UTF8 variant allocates strlen << 1 (~512 MB) and the JDK8 latin1 path char[strlen] (~512 MB). The allocating lines are pre-existing and untouched here — the hole is identically exploitable at the merge base — so this is filed as the next increment of the #7669 series rather than a blocker for this PR: same class, same fix shape.
Suggested fix:
checkLength(strlen, offset, end, "string length");immediately after each strlen = readLength() at the readAny/readString/readFieldName sites, before any allocation — a declared string byte-length larger than the remaining buffer is malformed by the same invariant (rejects nothing well-formed).
— qwen3.8-max via Qwen Code /review (v0.21.11)
| ? readLength() | ||
| : type - BC_ARRAY_FIX_MIN; | ||
|
|
||
| checkArrayLen(len, offset, end); |
There was a problem hiding this comment.
[Suggestion] No test exercises a truncated BC_ARRAY_FIX payload against the new inline checkArrayLen — the fix-length sub-branch of this ternary is guarded but unpinned at all three inline sites. Failure scenario: probe-verified at this commit — JSONB.parse(new byte[]{(byte) 0x9B, 0x01}) throws JSONException: array length out of range at offset 1/2: 7, available: 1 through the new guard (nothing in Issue7669 covers it), while JSONB.parseObject(new byte[]{(byte) 0x9B, 0x01}, int[].class) throws ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2, because startArray()'s fix branch (~1436-1439) returns type - BC_ARRAY_FIX_MIN with no check — the exact JSONException-vs-AIOOBE asymmetry testArrayDeclaredLengthNotAtBufferEnd pins as wrong on the guarded paths. If a future change narrows this guard into the type == BC_ARRAY arm (a plausible "optimization" — fix lengths are ≤ 15 and cannot OOM), the rejection silently reverts to AIOOBE and no test notices.
Suggested fix — pin the inline-site rejection:
assertThrows(JSONException.class, () -> JSONB.parse(new byte[]{(byte) 0x9B, 0x01}));and extend checkArrayLen into startArray()'s fix branch so the typed path rejects with JSONException too.
— qwen3.8-max via Qwen Code /review (v0.21.11)
| // new JSONArray(len) — now guarded by checkLength. Pin the guard's own | ||
| // message: without the guard a downstream "readAny overflow" JSONException | ||
| // would also satisfy a type-only assertion, letting the fix rot silently. | ||
| JSONException ex = assertThrows(JSONException.class, () -> JSONB.parse(UNTYPED_ARRAY_MAX_LEN)); |
There was a problem hiding this comment.
[Suggestion] Every new test asserts rejection of malformed input; none asserts acceptance of VALID input through the three inline guard sites (readObject/readAny/readArray). testArrayValidPayloadStillWorks pins the exact-fit boundary (len == end - offset) only via the startArray() typed path. Failure scenario: probe-verified — exact-fit {0xA4, 0x01, 0x00} is accepted as [0] at this commit, and replacing checkArrayLen at the readAny site with a hand-rolled len < 0 || len >= end - offset off-by-one false-rejects it while ALL existing tests in this file — including the message-pinning assertion below — stay green: a future strictness off-by-one would silently break valid exact-fit arrays.
Suggested fix: add acceptance round-trips through the three inline sites asserting values — JSONB.parse on an encoded exact-fit array, JSONB.parseObject(bytes) on a map with a valid array value, JSONB.parseArray on a valid nested array. (Exact fit is reachable at the readAny/readArray sites only; at the readObject site the trailing BC_OBJECT_END byte keeps remaining = len + 1, so pin it with a near-boundary payload there.)
— qwen3.8-max via Qwen Code /review (v0.21.11)
| len = valueType - BC_ARRAY_FIX_MIN; | ||
| } | ||
|
|
||
| checkArrayLen(len, offset, end); |
There was a problem hiding this comment.
[Suggestion] This guard sits one line below the unchecked bytes[offset] read of the array's length-type byte, so a payload truncated exactly at a BC_ARRAY header still escapes as a raw ArrayIndexOutOfBoundsException — the guard never executes for that input shape. Failure scenario: probe-verified at this commit — JSONB.parseObject(new byte[]{(byte) 0xA6, 0x4A, 0x6B, (byte) 0xA4}) throws ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4 at readObject:396 with no guard frame in the stack; JSONB.parse(new byte[]{(byte) 0xA4}) and JSONB.parseArray(new byte[]{(byte) 0xA4, 0x01, (byte) 0xA4}) AIOOBE inside readLength:197. The control probe (the declared-length overflow payload) throws JSONException through the full checkArrayLen → checkLength → throwLengthOutOfRange chain, so the guard works for its claimed case but is unreachable one byte shorter; the same class applies at the sibling inline sites (~930 readAny, ~1103 readArray). The throwing reads are pre-existing (byte-identical at the merge base) and truncation AIOOBEs exist reader-wide for every unchecked marker, so this is scoped as an adjacent follow-up — but the three sites this PR guards still leak raw AIOOBE one line above their new guards.
Suggested fix: reject before the length-type byte read — most leverage is one offset >= end check inside readLength() itself (covers the readAny/readArray callers), plus one before bytes[offset] at readObject:396 (Int32Num fast path, never calls readLength()); can land with the truncated-fix-array follow-up above since the fix shape is shared.
— qwen3.8-max via Qwen Code /review (v0.21.11)
skipValue() and skipName() consumed stream-declared lengths with no remaining-buffer check — the same defect class this PR closes elsewhere, flagged as the round-2 Critical: - BC_BINARY / long-string arms: checkLength before offset += - BC_OBJECT loop: fail closed at end of input, checkLength in the length-prefixed item arms (a negative length previously rewound offset and spun the loop forever on a 13-byte payload) - BC_ARRAY arm: checkArrayLen + fail closed at end of input, checkLength in the length-prefixed element arm - skipName() long-string arm: checkLength before offset += - readObject()/readAny() BC_ARRAY arms: reject a stream that ends right after the BC_ARRAY type byte (R2-4) codeSize (javap): skipValue 897 -> 1043, skipName 154 -> 172; both methods stay on the same side of the C1/C2 inline thresholds, so no inlining regression — the added work is two compares per skip. Tests: 13 new cases in Issue7669 replaying the three probe-verified failure shapes (huge BC_BINARY declared length, negative string length rewind, truncated array/object) plus valid-payload acceptance through skipValue() and the JSONValidator path.
R2-5 addressed in c8fbd5b: skipValue()/skipName() now bound every stream-declared length via the PR own checkLength/checkArrayLen (BC_BINARY, long-string, BC_OBJECT item arms, BC_ARRAY arm + element loop) and fail closed as JSONException at end of input; the three probe-verified failure shapes (huge BC_BINARY declared length, negative-length rewind loop, billion-iteration array spin) are replayed as deterministic tests. R2-4 addressed: readObject()/readAny() BC_ARRAY arms reject a stream ending right after the type byte. R2-2/R2-3 addressed: 13 new Issue7669 cases cover truncated payloads and valid-payload acceptance through skipValue() and JSONValidator. codeSize skipValue 897->1043, skipName 154->172, no inline-threshold crossing. CI 15/15 SUCCESS on head c8fbd5b. Dismissing stale round-2 review.
Summary
Follow-up to #7733 (same 7669 series: #7696 / #7705 / #7733).
PR #7733 added a
checkLengthremaining-buffer guard tostartArray()to stop theBC_ARRAYdeclared-length pre-allocation OOM. The reviewer (review-4842883034, suggestion R2-1) correctly pointed out that three inlineBC_ARRAYdecode sites never callstartArray()and therefore still pre-allocatenew JSONArray(len)/new ArrayList(len)with no remaining-buffer check:readObject()map-value branch (~line 392)readAny()value branch (~line 927)readArray()element branch (~line 1099)This PR folds the same
checkLength(offset, end, len)guard into those three inline sites.Reproducer
A 6-byte
BC_ARRAYpayload declaring ~268M elements against a tiny buffer, e.g.previously pre-allocated a ~1GiB
Object[]and OOM'd under a constrained heap; it now throwsJSONException: array length out of range.Verification
Issue7669regression tests added for all three paths:testUntypedArrayDeclaredLengthOOM_readAny(JSONB.parse -> readAny)testUntypedArrayDeclaredLengthOOM_readObject(JSONB.parseObject -> readObject)testUntypedArrayDeclaredLengthOOM_readArray(JSONB.parseArray -> readArray)mvn -pl core test -Dtest=Issue7669→ 20/20 pass, 0 Checkstyle violations.