diff --git a/docs/PDF-FORMAT.md b/docs/PDF-FORMAT.md index e9bff194..4890112b 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 and IHDR, each side ≤ 8,192 px, ≤ 16,777,216 px (4096²) | +| 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²) | | report at export | ≤ 500 observations, ≤ 8 views per observation | | SVG sanitiser | ≤ 20,000 elements, nesting ≤ 64, ≤ 256 ``, blur `stdDeviation` ≤ 100 | @@ -185,9 +185,14 @@ link action: pdf-lib does not escape a literal string, so the engine writes the URI as a hex string and the schema refuses the characters that could close a literal. The export re-validates the branding and the labels it receives (`ArchiveExportError('branding_invalid')` before any page is -drawn), even from an archive that passed the reader. A PNG logo whose header -is missing, wrong or over the pixel budget is never decoded: that slot alone -prints its fallback text and the export reports `logo_failed`. +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`. ### Known limits @@ -196,9 +201,11 @@ prints its fallback text and the export reports `logo_failed`. attachment is even looked at. The 50 MiB file cap bounds the input, not the expansion. Mitigation planned: parse in a Worker, or locate the attachment without a full load. -- `` expansion is bounded by the rasterizer (resvg refuses an - oversized tree), not by the sanitiser, which only counts the `` - elements (≤ 256). +- `` expansion is bounded by the rasterizer, not by the sanitiser, + which only counts the `` elements (≤ 256). resvg (tests) refuses an + oversized tree; the production path is the browser rasterizer + (`apps/app/src/pdf/browserRasterizer.ts`, `Image` + canvas), whose + limits on `` expansion are not measured. - Report v3 collections are not capped on read; the export refuses above 500 observations and 8 views per observation. diff --git a/packages/pdf/src/branding.ts b/packages/pdf/src/branding.ts index 02eac374..2972e151 100644 --- a/packages/pdf/src/branding.ts +++ b/packages/pdf/src/branding.ts @@ -5,20 +5,34 @@ import { renderBrandingSvg } from './svg/view' /** * The branding images embedded once per document. A PNG is decoded from - * its base64 once its header fits the pixel budget; an SVG is sanitised and - * rasterised at the view width. Each slot fails alone: the page prints the - * credit's fallback text instead and the export reports a `logo_failed` - * warning. + * its base64 once its header and chunk list fit the pixel budget; an SVG is + * sanitised and rasterised at the view width. Each slot fails alone: the + * page prints the credit's fallback text instead and the export reports a + * `logo_failed` warning. */ /** A logo PNG is at most 4096² pixels and 8192 px a side (STEP6 §15). */ export const PNG_CAPS = { side: 8192, pixels: 4096 * 4096 } as const const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a] -const IHDR_TYPE = 0x49484452 -const IHDR_END = 24 +/** A chunk is length (4), type (4), data (length), CRC (4). */ +const CHUNK_HEAD = 8 +const CHUNK_OVERHEAD = 12 +const IHDR_LENGTH = 13 +const IHDR_END = PNG_SIGNATURE.length + CHUNK_OVERHEAD + IHDR_LENGTH -export type PngHeaderIssue = 'signature' | 'dimensions' +/** The big-endian uint32 a four-letter chunk type reads as. */ +const chunkType = (name: string): number => + [...name].reduce((acc, char) => acc * 256 + char.charCodeAt(0), 0) + +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), +) + +export type PngHeaderIssue = 'signature' | 'dimensions' | 'chunks' export type LogoSlot = Extract['slot'] @@ -37,20 +51,43 @@ export interface BrandingImages { } /** - * Why a PNG is refused before any decoding, or null when its header fits - * the budget: the signature and the IHDR chunk must be there, and the - * announced width × height must stay under `PNG_CAPS`. The decoder would - * otherwise allocate the full bitmap of whatever size the header claims. + * 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. */ export function pngHeaderIssue(bytes: Uint8Array): PngHeaderIssue | null { if (bytes.byteLength < IHDR_END) return 'signature' if (PNG_SIGNATURE.some((byte, i) => bytes[i] !== byte)) return 'signature' const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength) + if (view.getUint32(8) !== IHDR_LENGTH) return 'signature' if (view.getUint32(12) !== IHDR_TYPE) return 'signature' const width = view.getUint32(16) const height = view.getUint32(20) if (width > PNG_CAPS.side || height > PNG_CAPS.side) return 'dimensions' if (width * height > PNG_CAPS.pixels) return 'dimensions' + return chunkListIssue(view) +} + +/** + * 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. + */ +function chunkListIssue(view: DataView): PngHeaderIssue | null { + let offset = IHDR_END + while (offset < view.byteLength) { + if (offset + CHUNK_HEAD > view.byteLength) return 'chunks' + 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 + } return null } diff --git a/packages/pdf/src/render/linkAnnotation.ts b/packages/pdf/src/render/linkAnnotation.ts index 8c9c2dc0..d3c53da3 100644 --- a/packages/pdf/src/render/linkAnnotation.ts +++ b/packages/pdf/src/render/linkAnnotation.ts @@ -1,4 +1,5 @@ import { PDFName, PDFHexString, type PDFPage } from 'pdf-lib' +import { ArchiveExportError } from '../errors' export interface LinkRect { x: number @@ -8,6 +9,29 @@ export interface LinkRect { url: string } +/** Printable ASCII without the space: what the branding URL schema allows. */ +const ASCII_MIN = 0x21 +const ASCII_MAX = 0x7e + +/** + * The URL as the hex form of its ASCII bytes, one byte per character. + * `PDFHexString.fromText` would write UTF-16BE with a BOM, which readers + * that take `/URI` as raw bytes (poppler) turn into a dead link. A code + * point outside printable ASCII cannot reach the sink: the schema refuses + * it upstream, so it means the branding bypassed validation. + */ +function asciiHexOf(url: string): string { + let hex = '' + for (const char of url) { + const code = char.codePointAt(0) ?? 0 + if (code < ASCII_MIN || code > ASCII_MAX) { + throw new ArchiveExportError('branding_invalid', 'url') + } + hex += code.toString(16).padStart(2, '0') + } + return hex +} + /** * A clickable `/Link` annotation opening `url`, appended to the page's * Annots. The URI is written as a hex string: pdf-lib does not escape `(`, @@ -20,7 +44,7 @@ export function addLinkAnnotation(page: PDFPage, rect: LinkRect): void { const actionDict = context.obj({ Type: 'Action', S: 'URI', - URI: PDFHexString.fromText(rect.url), + URI: PDFHexString.of(asciiHexOf(rect.url)), }) const annotDict = context.obj({ diff --git a/packages/pdf/tests/security.test.ts b/packages/pdf/tests/security.test.ts index aac3e018..035ca9b1 100644 --- a/packages/pdf/tests/security.test.ts +++ b/packages/pdf/tests/security.test.ts @@ -482,15 +482,55 @@ function reexportOptions() { } } +/** The same payload without spaces: PDF syntax needs none, and the sink lets it through to the hex string. */ +const TIGHT_INJECTION_URL = INJECTION_URL.replaceAll(' ', '') + +/** The saved bytes of a one-page PDF holding one link to `url`, objects uncompressed so the bytes can be read. */ +async function savedLink(url: string): Promise { + const doc = await PDFDocument.create() + addLinkAnnotation(doc.addPage(), { x: 0, y: 0, width: 10, height: 10, url }) + return doc.save({ useObjectStreams: false }) +} + +/** `` of the URL's ASCII bytes, as the sink must write `/URI`. */ +const asciiHex = (url: string): string => + Array.from(url, (c) => c.charCodeAt(0).toString(16).padStart(2, '0')).join('') + describe('branding URL injection (HIGH)', () => { + it('writes /URI as the hex of the ASCII bytes, no UTF-16 BOM, and reloads to the URL', async () => { + const url = 'https://faunosteo.com' + const bytes = await savedLink(url) + const raw = Buffer.from(bytes).toString('latin1') + const uriMatch = /\/URI\s*<([0-9A-Fa-f]+)>/.exec(raw) + expect(uriMatch?.[1]?.toLowerCase()).toBe(asciiHex(url)) + expect(uriMatch?.[1]?.toUpperCase().startsWith('FEFF')).toBe(false) + expect(Buffer.from(uriMatch![1]!, 'hex').toString('latin1')).toBe(url) + const [link] = await readLinks(bytes) + expect(link?.uri).toBe(url) + }) + + it('a URL with a code point above 0x7e or below 0x21 throws branding_invalid at the sink', async () => { + for (const url of [ + 'https://faunosté.com', + 'https://a.example/ b', + INJECTION_URL, + 'https://a.example/\u00ff', + ]) { + await expect(savedLink(url), url).rejects.toMatchObject({ + kind: 'branding_invalid', + }) + await expect(savedLink(url), url).rejects.toBeInstanceOf( + ArchiveExportError, + ) + } + }) + it('the link sink alone keeps the whole URL inside the /URI string', async () => { - const doc = await PDFDocument.create() - const rect = { x: 0, y: 0, width: 10, height: 10, url: INJECTION_URL } - addLinkAnnotation(doc.addPage(), rect) - const bytes = await doc.save() + const bytes = await savedLink(TIGHT_INJECTION_URL) const raw = Buffer.from(bytes).toString('latin1') expect(raw).not.toContain('/JavaScript') expect(raw).not.toContain('/Next') + expect(raw).not.toContain('/JS') const reloaded = await PDFDocument.load(bytes) expect(javaScriptActions(reloaded)).toEqual([]) const action = reloaded @@ -501,7 +541,7 @@ describe('branding URL injection (HIGH)', () => { expect(action.has(PDFName.of('Next'))).toBe(false) expect(action.get(PDFName.of('S'))).toBe(PDFName.of('URI')) const [link] = await readLinks(bytes) - expect(link?.uri).toBe(INJECTION_URL) + expect(link?.uri).toBe(TIGHT_INJECTION_URL) }) it('exportFromEnvelope refuses the URL before drawing anything: branding_invalid', async () => { @@ -556,6 +596,27 @@ function pngHeader( return bytes } +/** One chunk: length, four-letter type, `data`, a zero CRC. */ +function pngChunk(type: string, data: Uint8Array): Uint8Array { + const bytes = new Uint8Array(12 + data.byteLength) + new DataView(bytes.buffer).setUint32(0, data.byteLength) + bytes.set( + Array.from(type, (c) => c.charCodeAt(0)), + 4, + ) + bytes.set(data, 8) + return bytes +} + +const concat = (...parts: Uint8Array[]): Uint8Array => + Uint8Array.from(Buffer.concat(parts.map((p) => Buffer.from(p)))) + +/** 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))) +} + describe('PNG budget (MEDIUM)', () => { it.each([ ['8193 × 1 → dimensions', 8193, 1, 'dimensions'], @@ -583,33 +644,70 @@ describe('PNG budget (MEDIUM)', () => { if (asset?.kind !== 'png') throw new Error('png expected') expect(pngHeaderIssue(Buffer.from(asset.base64, 'base64'))).toBeNull() } + const touchIcon = readFileSync(resolve(PUBLIC_DIR, 'apple-touch-icon.png')) + expect(pngHeaderIssue(new Uint8Array(touchIcon))).toBeNull() }) - it('an oversized header logo fails alone with logo_failed and never reaches embedPng', async () => { - const branding = nologosBranding() - const huge = pngHeader(16_384, 16_384) - branding.headerLogo = { - kind: 'png', - base64: Buffer.from(huge).toString('base64'), - } - branding.footerLogo = { - kind: 'png', - base64: Buffer.from(ONE_PX_PNG).toString('base64'), - } - const embedPng = vi.spyOn(PDFDocument.prototype, 'embedPng') - try { - const { warnings } = await exportReportArchive({ - ...baseInput(golden.reports.demo, golden.snapshots.demo), - branding, - }) - expect(warnings).toEqual([{ kind: 'logo_failed', slot: 'headerLogo' }]) - const sizes = embedPng.mock.calls.map( - ([png]) => (png as Uint8Array).byteLength, - ) - expect(sizes).not.toContain(huge.byteLength) - expect(sizes).toContain(ONE_PX_PNG.byteLength) - } finally { - embedPng.mockRestore() + it('the chunk walk refuses a second IHDR, an APNG acTL and a length past the buffer', () => { + expect(pngHeaderIssue(doubledIhdrPng())).toBe('chunks') + const apng = concat( + pngHeader(1, 1), + pngChunk('acTL', new Uint8Array(8)), + pngChunk('IEND', new Uint8Array(0)), + ) + expect(pngHeaderIssue(apng)).toBe('chunks') + for (const type of ['fcTL', 'fdAT']) { + const frame = concat(pngHeader(1, 1), pngChunk(type, new Uint8Array(4))) + expect(pngHeaderIssue(frame), type).toBe('chunks') } + const idat = pngChunk('IDAT', new Uint8Array(16)) + new DataView(idat.buffer).setUint32(0, 1_000_000) + 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() + const shortIhdr = pngHeader(1, 1) + new DataView(shortIhdr.buffer).setUint32(8, 12) + expect(pngHeaderIssue(shortIhdr)).toBe('signature') }) + + it.each([ + ['an oversized header logo', () => pngHeader(16_384, 16_384)], + ['a doubled-IHDR header logo', doubledIhdrPng], + ])( + '%s fails alone with logo_failed and never reaches embedPng', + async (_name, make) => { + const branding = nologosBranding() + const huge = make() + branding.headerLogo = { + kind: 'png', + base64: Buffer.from(huge).toString('base64'), + } + branding.footerLogo = { + kind: 'png', + base64: Buffer.from(ONE_PX_PNG).toString('base64'), + } + const embedPng = vi.spyOn(PDFDocument.prototype, 'embedPng') + try { + const { warnings } = await exportReportArchive({ + ...baseInput(golden.reports.demo, golden.snapshots.demo), + branding, + }) + expect(warnings).toEqual([{ kind: 'logo_failed', slot: 'headerLogo' }]) + const base64 = (png: Uint8Array) => Buffer.from(png).toString('base64') + const embedded = embedPng.mock.calls.map(([png]) => + base64(png as Uint8Array), + ) + expect(embedded).not.toContain(base64(huge)) + expect(embedded).toContain(base64(ONE_PX_PNG)) + } finally { + embedPng.mockRestore() + } + }, + ) })