fix(pdf): security hardening — hex-encoded link URIs, strict branding URL schema, branding and labels re-validated at export, PNG dimension budget, CSS escape and parenthesis rules in the sanitiser, finite raster size, file size checked before read
This commit is contained in:
1 parent
4930704d8a
commit
1f417b21fd
12 files changed
+437
-25
No files matched your search
@@ -5,11 +5,21 @@ import { renderBrandingSvg } from './svg/view'
|
||||
|
||||
/**
|
||||
* The branding images embedded once per document. A PNG is decoded from
|
||||
* its base64; 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 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.
|
||||
*/
|
||||
|
||||
/** 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
|
||||
|
||||
export type PngHeaderIssue = 'signature' | 'dimensions'
|
||||
|
||||
export type LogoSlot = Extract<ExportWarning, { kind: 'logo_failed' }>['slot']
|
||||
|
||||
export interface CreditAsset {
|
||||
@@ -26,6 +36,24 @@ export interface BrandingImages {
|
||||
partner: CreditAsset | null
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
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(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 null
|
||||
}
|
||||
|
||||
function base64ToBytes(base64: string): Uint8Array {
|
||||
const binary = atob(base64)
|
||||
const bytes = new Uint8Array(binary.length)
|
||||
@@ -38,7 +66,12 @@ async function embedImage(
|
||||
asset: ImageAsset,
|
||||
rasterizer: Rasterizer,
|
||||
): Promise<PDFImage> {
|
||||
if (asset.kind === 'png') return pdfDoc.embedPng(base64ToBytes(asset.base64))
|
||||
if (asset.kind === 'png') {
|
||||
const bytes = base64ToBytes(asset.base64)
|
||||
const issue = pngHeaderIssue(bytes)
|
||||
if (issue) throw new Error(`png refused: ${issue}`)
|
||||
return pdfDoc.embedPng(bytes)
|
||||
}
|
||||
const { svg, size } = renderBrandingSvg(asset.svg)
|
||||
return pdfDoc.embedPng(await rasterizer(svg, size))
|
||||
}
|
||||
|
||||
@@ -25,6 +25,8 @@ export type ArchiveExportErrorKind =
|
||||
| 'snapshot_too_large'
|
||||
| 'sheet_mismatch'
|
||||
| 'too_many_pages'
|
||||
/** The branding or the label set fails its schema (URLs included). */
|
||||
| 'branding_invalid'
|
||||
|
||||
export class ArchiveExportError extends Error {
|
||||
constructor(
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { PDFDocument } from 'pdf-lib'
|
||||
import {
|
||||
assertSnapshot,
|
||||
BrandingSchema,
|
||||
buildSheetIndex,
|
||||
ENVELOPE_FORMAT,
|
||||
ENVELOPE_VERSION,
|
||||
PdfLabelSetSchema,
|
||||
snapshotIndexSource,
|
||||
SnapshotError,
|
||||
type Report,
|
||||
@@ -43,6 +45,20 @@ export const PAGE_CAPS = {
|
||||
viewsPerObservation: 8,
|
||||
} as const
|
||||
|
||||
/**
|
||||
* Step 0: the branding and the labels pass their schemas again. They reach
|
||||
* the engine from an archive or from the application and end up in link
|
||||
* URIs and drawn text, so a caller cannot be trusted to have validated them.
|
||||
*/
|
||||
function assertBrandingAndLabels(input: ExportInput): void {
|
||||
if (!BrandingSchema.safeParse(input.branding).success) {
|
||||
throw new ArchiveExportError('branding_invalid', 'branding')
|
||||
}
|
||||
if (!PdfLabelSetSchema.safeParse(input.labels).success) {
|
||||
throw new ArchiveExportError('branding_invalid', 'labels')
|
||||
}
|
||||
}
|
||||
|
||||
/** Step 1: the snapshot gate, with every asset accepted by the sanitiser. */
|
||||
function checkedSnapshot(sheet: SheetSnapshot): SheetSnapshot {
|
||||
let parsed: SheetSnapshot
|
||||
@@ -161,6 +177,7 @@ async function drawPages(pages: Pages): Promise<void> {
|
||||
export async function exportReportArchive(
|
||||
input: ExportInput,
|
||||
): Promise<ExportResult> {
|
||||
assertBrandingAndLabels(input)
|
||||
const sheet = checkedSnapshot(input.sheet)
|
||||
assertExportable(input.report, sheet)
|
||||
const envelope = buildEnvelope(input, sheet)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { PDFName, PDFArray, PDFString, type PDFPage } from 'pdf-lib'
|
||||
import { PDFName, PDFHexString, type PDFPage } from 'pdf-lib'
|
||||
|
||||
export interface LinkRect {
|
||||
x: number
|
||||
@@ -8,14 +8,19 @@ export interface LinkRect {
|
||||
url: string
|
||||
}
|
||||
|
||||
/** A clickable `/Link` annotation opening `url`, appended to the page's Annots. */
|
||||
/**
|
||||
* 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 `(`,
|
||||
* `)` or `\` in a literal string, so a hostile URL could otherwise close
|
||||
* the literal and inject objects (a `/Next` JavaScript action, for one).
|
||||
*/
|
||||
export function addLinkAnnotation(page: PDFPage, rect: LinkRect): void {
|
||||
const context = page.doc.context
|
||||
|
||||
const actionDict = context.obj({
|
||||
Type: 'Action',
|
||||
S: 'URI',
|
||||
URI: PDFString.of(rect.url),
|
||||
URI: PDFHexString.fromText(rect.url),
|
||||
})
|
||||
|
||||
const annotDict = context.obj({
|
||||
@@ -26,7 +31,7 @@ export function addLinkAnnotation(page: PDFPage, rect: LinkRect): void {
|
||||
A: actionDict,
|
||||
})
|
||||
|
||||
const annots = page.node.lookup(PDFName.of('Annots'), PDFArray)
|
||||
const annots = page.node.Annots()
|
||||
if (annots) {
|
||||
annots.push(context.register(annotDict))
|
||||
} else {
|
||||
|
||||
@@ -5,10 +5,12 @@ import { SvgRejectedError } from '../errors'
|
||||
* Allowlist sanitiser for the sheet drawings and the branding SVGs
|
||||
* (STEP6 §15), on DOM Level 2 only. Elements and attributes outside the
|
||||
* inventory of the real assets plus structural needs are removed with
|
||||
* their subtree; `href` and `url(…)` must stay inside the document; a
|
||||
* `style` attribute may carry no external reference; the halo filters are
|
||||
* clamped. Element, nesting and `<use>` counters refuse an oversized tree.
|
||||
* The caller learns what was removed (names only, never values).
|
||||
* their subtree; `href` and `url(…)` must stay inside the document; no
|
||||
* value carries a backslash (a CSS escape such as `u\72l(` would hide a
|
||||
* reference from the rules below); a `style` or presentation attribute may
|
||||
* call no function but `url(#…)`; the halo filters are clamped. Element,
|
||||
* nesting and `<use>` counters refuse an oversized tree. The caller learns
|
||||
* what was removed (names only, never values).
|
||||
*/
|
||||
|
||||
export const SANITIZER_CAPS = {
|
||||
@@ -126,9 +128,42 @@ const ALLOWED_ATTRIBUTES = new Set([
|
||||
'style',
|
||||
])
|
||||
|
||||
/** Attributes whose value is CSS-like: a function call there is a reference or an exploit. */
|
||||
const PRESENTATION_ATTRIBUTES = new Set([
|
||||
'fill',
|
||||
'fill-opacity',
|
||||
'fill-rule',
|
||||
'stroke',
|
||||
'stroke-width',
|
||||
'stroke-linecap',
|
||||
'stroke-linejoin',
|
||||
'stroke-opacity',
|
||||
'stroke-dasharray',
|
||||
'stroke-dashoffset',
|
||||
'stroke-miterlimit',
|
||||
'opacity',
|
||||
'filter',
|
||||
'clip-path',
|
||||
'clip-rule',
|
||||
'mask',
|
||||
'display',
|
||||
'visibility',
|
||||
'color',
|
||||
'stop-color',
|
||||
'stop-opacity',
|
||||
'flood-color',
|
||||
'flood-opacity',
|
||||
'color-interpolation-filters',
|
||||
'font-family',
|
||||
'font-size',
|
||||
'font-weight',
|
||||
])
|
||||
|
||||
const LOCAL_REFERENCE = /^#[A-Za-z_][\w.:-]*$/
|
||||
const URL_FUNCTION = /url\(\s*['"]?\s*(.?)/gi
|
||||
const STYLE_FORBIDDEN = /expression\(|@import|javascript:|behavior:/i
|
||||
const LOCAL_URL_OPEN = /url\(\s*['"]?\s*#/gi
|
||||
const STYLE_FORBIDDEN =
|
||||
/expression\(|image-set\(|@import|javascript:|behavior:/i
|
||||
|
||||
export interface SanitizeOutcome {
|
||||
/** Removed element names and `element@attribute` pairs, in document order. */
|
||||
@@ -157,11 +192,20 @@ function hrefIsLocal(value: string): boolean {
|
||||
return LOCAL_REFERENCE.test(value.trim())
|
||||
}
|
||||
|
||||
/** Any `(` left once the `url(#` openings are gone is a function we never allow. */
|
||||
function callsOnlyLocalUrl(value: string): boolean {
|
||||
return !value.replace(LOCAL_URL_OPEN, '').includes('(')
|
||||
}
|
||||
|
||||
/** Whether an allowed attribute keeps its value, by name-specific rule. */
|
||||
function attributeAcceptable(name: string, value: string): boolean {
|
||||
if (value.includes('\\')) return false
|
||||
if (!urlsAreLocal(value)) return false
|
||||
if (name === 'href' || name === 'xlink:href') return hrefIsLocal(value)
|
||||
if (name === 'style') return !STYLE_FORBIDDEN.test(value)
|
||||
if (name === 'style') {
|
||||
return !STYLE_FORBIDDEN.test(value) && callsOnlyLocalUrl(value)
|
||||
}
|
||||
if (PRESENTATION_ATTRIBUTES.has(name)) return callsOnlyLocalUrl(value)
|
||||
return true
|
||||
}
|
||||
|
||||
|
||||
@@ -27,6 +27,11 @@ export interface RenderedSvg {
|
||||
size: RasterSize
|
||||
}
|
||||
|
||||
/** A usable dimension: finite and strictly positive (`1e999` parses to Infinity). */
|
||||
function isPositiveFinite(value: number | undefined): value is number {
|
||||
return value !== undefined && Number.isFinite(value) && value > 0
|
||||
}
|
||||
|
||||
/** Height over width of a `viewBox` value, or the fallback when unusable. */
|
||||
function aspectOf(viewBox: string | null): number {
|
||||
const parts = (viewBox ?? '')
|
||||
@@ -34,10 +39,14 @@ function aspectOf(viewBox: string | null): number {
|
||||
.split(/[\s,]+/)
|
||||
.map(Number)
|
||||
const [, , width, height] = parts
|
||||
if (parts.length !== 4 || !(width! > 0) || !(height! > 0)) {
|
||||
if (
|
||||
parts.length !== 4 ||
|
||||
!isPositiveFinite(width) ||
|
||||
!isPositiveFinite(height)
|
||||
) {
|
||||
return ASPECT_FALLBACK
|
||||
}
|
||||
return height! / width!
|
||||
return height / width
|
||||
}
|
||||
|
||||
export function rasterSizeOf(viewBox: string | null): RasterSize {
|
||||
|
||||
Reference in new issue
Block a user