diff --git a/docs/PDF-FORMAT.md b/docs/PDF-FORMAT.md index 4890112b..460c16d4 100644 --- a/docs/PDF-FORMAT.md +++ b/docs/PDF-FORMAT.md @@ -162,7 +162,7 @@ Two operations are distinct: | snapshot document | ≤ 64 views, ≤ 1,024 annotations, ≤ 8,192 finding nodes, depth ≤ 8, names ≤ 512 chars | | branding | PNG base64 ≤ 512 KiB, SVG ≤ 256 KiB, http(s) URLs ≤ 2,048 chars | | branding URL | `http(s)://` then printable ASCII only, without `"` `'` `(` `)` `<` `>` `\`, no space or control character | -| branding PNG | valid signature, one IHDR (13 bytes) first, no second IHDR or APNG chunk (`acTL`, `fcTL`, `fdAT`), no chunk past the buffer, each side ≤ 8,192 px, ≤ 16,777,216 px (4096²) | +| branding PNG | valid signature, one IHDR (13 bytes) first, then only `PLTE` `tRNS` `IDAT` `gAMA` `cHRM` `sRGB` `sBIT` `pHYs` `bKGD`, no chunk past the buffer, an empty `IEND` as the last bytes, each side ≤ 8,192 px, ≤ 16,777,216 px (4096²) | | report at export | ≤ 500 observations, ≤ 8 views per observation | | SVG sanitiser | ≤ 20,000 elements, nesting ≤ 64, ≤ 256 ``, blur `stdDeviation` ≤ 100 | @@ -189,10 +189,17 @@ drawn), even from an archive that passed the reader. The URI itself is the hex form of the URL's ASCII bytes (`<68747470…>`), not UTF-16 with a BOM, so readers that take `/URI` as raw bytes (poppler) follow it. A PNG logo is checked before decoding: the signature and a first 13-byte IHDR, then the -chunk list is walked to `IEND`; a second IHDR (the decoder would size its -buffer from the last one), an APNG chunk, a chunk length past the end of -the buffer or a header over the pixel budget refuses the slot. That slot -alone prints its fallback text and the export reports `logo_failed`. +chunk list is walked and must end on an empty `IEND` that closes the file. +Only the chunk types the decoder reads by fixed offsets or by declared +length are accepted (`PLTE`, `tRNS`, `IDAT`, `IEND`, `gAMA`, `cHRM`, `sRGB`, +`sBIT`, `pHYs`, `bKGD`); a second IHDR (the decoder would size its buffer +from the last one), an APNG chunk, a text or profile chunk (`tEXt`, `iTXt`, +`zTXt`, `iCCP`: the decoder scans them for a NUL byte and never stops when +none follows in the buffer), an unknown type, a chunk length past the end +of the buffer, a missing IEND or bytes after it, or a header over the pixel +budget refuses the slot. The archive accepts only PNGs ending on IEND, even +though the decoder reads a PNG without one. That slot alone prints its +fallback text and the export reports `logo_failed`. ### Known limits diff --git a/packages/pdf/src/branding.ts b/packages/pdf/src/branding.ts index 2972e151..362388fb 100644 --- a/packages/pdf/src/branding.ts +++ b/packages/pdf/src/branding.ts @@ -27,9 +27,26 @@ const chunkType = (name: string): number => const IHDR_TYPE = chunkType('IHDR') const IEND_TYPE = chunkType('IEND') -/** A second IHDR resizes the decoder's buffer; APNG frames are not a logo. */ -const FORBIDDEN_CHUNKS = new Set( - ['IHDR', 'acTL', 'fcTL', 'fdAT'].map(chunkType), +/** + * The chunk types UPNG reads by fixed offsets or by declared length. A + * second IHDR resizes the decoder's buffer, APNG frames are not a logo, and + * every text or profile chunk (`tEXt`, `iTXt`, `zTXt`, `iCCP`) is read with + * `_bin.nextZero` (`while (data[p] != 0) p++`), which never stops when no + * NUL byte follows in the buffer: all of them stay out of the list. + */ +const ALLOWED_CHUNKS = new Set( + [ + 'PLTE', + 'tRNS', + 'IDAT', + 'IEND', + 'gAMA', + 'cHRM', + 'sRGB', + 'sBIT', + 'pHYs', + 'bKGD', + ].map(chunkType), ) export type PngHeaderIssue = 'signature' | 'dimensions' | 'chunks' @@ -54,9 +71,10 @@ export interface BrandingImages { * Why a PNG is refused before any decoding, or null when it fits the * budget: the signature and a first IHDR chunk of 13 bytes must be there, * the announced width × height must stay under `PNG_CAPS`, and the chunk - * list must hold no second IHDR, no APNG chunk and no length past the end - * of the buffer. The decoder would otherwise allocate the full bitmap of - * whatever size the last IHDR claims. + * list must hold only allowlisted types, none past the end of the buffer, + * closed by an `IEND` that ends the file. The decoder would otherwise + * allocate the bitmap of whatever size the last IHDR claims, or scan past + * the buffer for a NUL byte that is not there. */ export function pngHeaderIssue(bytes: Uint8Array): PngHeaderIssue | null { if (bytes.byteLength < IHDR_END) return 'signature' @@ -72,23 +90,26 @@ export function pngHeaderIssue(bytes: Uint8Array): PngHeaderIssue | null { } /** - * Walks the chunks after the first IHDR until `IEND` or the end of the - * buffer. UPNG applies every IHDR it meets and sizes its buffer from the - * last one, so the first header alone proves nothing; a declared length - * that overruns the buffer, or a truncated chunk head, is refused as well. + * Walks the chunks after the first IHDR to an `IEND` of length 0 that ends + * the buffer exactly. Any type outside `ALLOWED_CHUNKS` (a second IHDR, an + * APNG chunk, a `tEXt`/`iTXt` whose missing NUL would spin UPNG's + * `nextZero` forever, an unknown type), a declared length past the buffer, + * a truncated chunk head, a missing IEND or bytes after it are refused. */ function chunkListIssue(view: DataView): PngHeaderIssue | null { let offset = IHDR_END - while (offset < view.byteLength) { - if (offset + CHUNK_HEAD > view.byteLength) return 'chunks' + while (offset + CHUNK_HEAD <= view.byteLength) { const length = view.getUint32(offset) const type = view.getUint32(offset + 4) - if (offset + CHUNK_OVERHEAD + length > view.byteLength) return 'chunks' - if (type === IEND_TYPE) return null - if (FORBIDDEN_CHUNKS.has(type)) return 'chunks' - offset += CHUNK_OVERHEAD + length + const next = offset + CHUNK_OVERHEAD + length + if (next > view.byteLength) return 'chunks' + if (!ALLOWED_CHUNKS.has(type)) return 'chunks' + if (type === IEND_TYPE) { + return length === 0 && next === view.byteLength ? null : 'chunks' + } + offset = next } - return null + return 'chunks' } function base64ToBytes(base64: string): Uint8Array { diff --git a/packages/pdf/tests/security.test.ts b/packages/pdf/tests/security.test.ts index 035ca9b1..5fd599e0 100644 --- a/packages/pdf/tests/security.test.ts +++ b/packages/pdf/tests/security.test.ts @@ -611,10 +611,31 @@ function pngChunk(type: string, data: Uint8Array): Uint8Array { const concat = (...parts: Uint8Array[]): Uint8Array => Uint8Array.from(Buffer.concat(parts.map((p) => Buffer.from(p)))) +const IEND = pngChunk('IEND', new Uint8Array(0)) +const IDAT = pngChunk('IDAT', new Uint8Array(16)) + /** A 1×1 header followed by a second IHDR announcing 10000 × 10000, then IEND. */ function doubledIhdrPng(): Uint8Array { const second = pngHeader(10_000, 10_000).subarray(8) - return concat(pngHeader(1, 1), second, pngChunk('IEND', new Uint8Array(0))) + return concat(pngHeader(1, 1), second, IEND) +} + +/** + * The auditor's PoC: a valid 1×1 PNG whose IEND is replaced by a `tEXt` + * chunk "AAAA" with a non-zero CRC and no NUL byte, so UPNG's `nextZero` + * never stops (`ONE_PX_PNG` minus its 12-byte IEND). + */ +function textWithoutNulPng(): Uint8Array { + const text = pngChunk('tEXt', new TextEncoder().encode('AAAA')) + text.fill(0xff, text.byteLength - 4) + return concat(ONE_PX_PNG.subarray(0, ONE_PX_PNG.byteLength - 12), text) +} + +/** The second PoC: an `iTXt` chunk, then an IEND of length 0x010101 with a non-zero payload. */ +function itxtThenFatIendPng(): Uint8Array { + const itxt = pngChunk('iTXt', new TextEncoder().encode('kw')) + const fatIend = pngChunk('IEND', new Uint8Array(0x010101).fill(1)) + return concat(pngHeader(1, 1), IDAT, itxt, fatIend) } describe('PNG budget (MEDIUM)', () => { @@ -626,7 +647,7 @@ describe('PNG budget (MEDIUM)', () => { ['4096 × 4096 → accepted', 4096, 4096, null], ['8192 × 2048 → accepted', 8192, 2048, null], ])('%s', (_name, width, height, issue) => { - expect(pngHeaderIssue(pngHeader(width, height))).toBe(issue) + expect(pngHeaderIssue(concat(pngHeader(width, height), IEND))).toBe(issue) }) it('a wrong signature or a truncated header is refused; the real logos pass', () => { @@ -653,11 +674,15 @@ describe('PNG budget (MEDIUM)', () => { const apng = concat( pngHeader(1, 1), pngChunk('acTL', new Uint8Array(8)), - pngChunk('IEND', new Uint8Array(0)), + IEND, ) expect(pngHeaderIssue(apng)).toBe('chunks') for (const type of ['fcTL', 'fdAT']) { - const frame = concat(pngHeader(1, 1), pngChunk(type, new Uint8Array(4))) + const frame = concat( + pngHeader(1, 1), + pngChunk(type, new Uint8Array(4)), + IEND, + ) expect(pngHeaderIssue(frame), type).toBe('chunks') } const idat = pngChunk('IDAT', new Uint8Array(16)) @@ -665,20 +690,50 @@ describe('PNG budget (MEDIUM)', () => { expect(pngHeaderIssue(concat(pngHeader(1, 1), idat))).toBe('chunks') const partialHead = concat(pngHeader(1, 1), new Uint8Array(5)) expect(pngHeaderIssue(partialHead)).toBe('chunks') - const wellFormed = concat( - pngHeader(1, 1), - pngChunk('IDAT', new Uint8Array(16)), - pngChunk('IEND', new Uint8Array(0)), - ) - expect(pngHeaderIssue(wellFormed)).toBeNull() + expect(pngHeaderIssue(concat(pngHeader(1, 1), IDAT, IEND))).toBeNull() const shortIhdr = pngHeader(1, 1) new DataView(shortIhdr.buffer).setUint32(8, 12) expect(pngHeaderIssue(shortIhdr)).toBe('signature') }) + it('a chunk UPNG reads with nextZero, or any type outside the allowlist, is refused', () => { + expect(pngHeaderIssue(textWithoutNulPng())).toBe('chunks') + expect(pngHeaderIssue(itxtThenFatIendPng())).toBe('chunks') + for (const type of ['tIME', 'zTXt', 'iCCP', 'abCD']) { + const png = concat( + pngHeader(1, 1), + IDAT, + pngChunk(type, new Uint8Array(7)), + IEND, + ) + expect(pngHeaderIssue(png), type).toBe('chunks') + } + }) + + it('the list must end on an empty IEND that closes the buffer; ancillary chunks pass', () => { + const valid = concat(pngHeader(1, 1), IDAT, IEND) + expect(pngHeaderIssue(concat(valid, new Uint8Array([0])))).toBe('chunks') + expect(pngHeaderIssue(concat(pngHeader(1, 1), IDAT))).toBe('chunks') + expect( + pngHeaderIssue( + concat(pngHeader(1, 1), IDAT, pngChunk('IEND', new Uint8Array(1))), + ), + ).toBe('chunks') + const ancillary = concat( + pngHeader(1, 1), + pngChunk('gAMA', new Uint8Array(4)), + pngChunk('pHYs', new Uint8Array(9)), + pngChunk('sRGB', new Uint8Array(1)), + IDAT, + IEND, + ) + expect(pngHeaderIssue(ancillary)).toBeNull() + }) + it.each([ - ['an oversized header logo', () => pngHeader(16_384, 16_384)], + ['an oversized header logo', () => concat(pngHeader(16_384, 16_384), IEND)], ['a doubled-IHDR header logo', doubledIhdrPng], + ['a tEXt-without-NUL header logo (UPNG would spin)', textWithoutNulPng], ])( '%s fails alone with logo_failed and never reaches embedPng', async (_name, make) => { @@ -692,7 +747,18 @@ describe('PNG budget (MEDIUM)', () => { kind: 'png', base64: Buffer.from(ONE_PX_PNG).toString('base64'), } - const embedPng = vi.spyOn(PDFDocument.prototype, 'embedPng') + // The spy refuses the hostile bytes itself: a regression that lets + // them through fails on the assertion below instead of spinning the + // worker in UPNG's nextZero, which no vitest timeout can interrupt. + const realEmbedPng = PDFDocument.prototype.embedPng + const embedPng = vi + .spyOn(PDFDocument.prototype, 'embedPng') + .mockImplementation(function (this: PDFDocument, png) { + if (Buffer.from(png as Uint8Array).equals(Buffer.from(huge))) { + throw new Error('hostile png reached embedPng') + } + return realEmbedPng.call(this, png) + }) try { const { warnings } = await exportReportArchive({ ...baseInput(golden.reports.demo, golden.snapshots.demo), @@ -709,5 +775,6 @@ describe('PNG budget (MEDIUM)', () => { embedPng.mockRestore() } }, + 10_000, ) })