Tighten xref stream field-width validation

Reject negative widths and require at least one byte per entry. This bounds
entry parsing by the decoded stream length.
This commit is contained in:
Calixte Denizet
2026-09-19 18:17:51 +02:00
parent 37fc214557
commit d1e416df36
2 changed files with 21 additions and 3 deletions
+5 -3
View File
@@ -358,10 +358,12 @@ class XRef {
if (!Number.isInteger(first) || !Number.isInteger(n)) {
throw new FormatError(`Invalid XRef range fields: ${first}, ${n}`);
}
// Each entry must consume a byte to bound the loop by the stream length.
if (
!Number.isInteger(typeFieldWidth) ||
!Number.isInteger(offsetFieldWidth) ||
!Number.isInteger(generationFieldWidth)
![typeFieldWidth, offsetFieldWidth, generationFieldWidth].every(
width => Number.isInteger(width) && width >= 0
) ||
typeFieldWidth + offsetFieldWidth + generationFieldWidth === 0
) {
throw new FormatError(
`Invalid XRef entry fields length: ${first}, ${n}`
+16
View File
@@ -18,6 +18,7 @@ import { Dict, Name, Ref } from "../../src/core/primitives.js";
import { PDFDocument } from "../../src/core/document.js";
import { StringStream } from "../../src/core/stream.js";
import { XRef } from "../../src/core/xref.js";
import { XRefParseException } from "../../src/core/core_utils.js";
describe("document", function () {
describe("Page", function () {
@@ -72,6 +73,21 @@ describe("document", function () {
expect(xref.readXRef()).toBeInstanceOf(Dict);
expect(xref.countUpdatesAfter(0)).toBeNull();
});
it("rejects an xref stream whose entries have zero width", function () {
const stream = new StringStream(
"%PDF-1.5\n" +
"1 0 obj\n" +
"<</Type/XRef/W[0 0 0]/Index[0 10000000]/Size 10000001" +
"/Root 2 0 R/Length 0>>\n" +
"stream\nendstream\nendobj\n" +
"startxref\n9\n%%EOF\n"
);
const xref = new XRef(stream, {});
xref.setStartXRef(9);
expect(() => xref.readXRef()).toThrowError(XRefParseException);
});
});
describe("PDFDocument", function () {