Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions design/security.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,20 @@ What keeps a hostile package in its place: entry names, `untrusted` and the cont
can never carry `..` to the worker — the URL parser collapses `..` and `%2e%2e` alike before
the request is made. `normalizeRequestPath` still decodes before validating, as defence in
depth, but the attack it is named for arrives through the central directory.
- **An entry inflates no further than the size its archive declares, and the worker parses no JSON
over 16 MB.** zip.js refuses an entry that runs past its declared size. The native
`DecompressionStream` knows none, and extractions, the warm and an archive still downloading
inflate with it: `inflated` counts the output, a stored entry's too, and fails it with
`bad-archive` (`heldTo`). Unheld, 65 kB inflates to 64 MB under a declared 10 bytes and is
stored as complete; without end, it fills the store, and each refused write evicts another idle
package. `PackageReader.json` refuses, unread, an `h5p.json` or `library.json` that declares or
carries more than `PARSED_MAX_SIZE`, since parsing holds it whole in the Service Worker and a
few kB inflate to gigabytes; a `content.json` over it is treated as one that cannot be parsed,
and the addon scan passes over such a `library.json`, as over one that does not parse. The
largest `content.json` of 89 real packages is 150 kB. Not bounded: the archive's index, which
zip.js reads whole whatever its entry count, and an entry of an honest, enormous size, which is
a large package like any other and evicts idle ones to fit. `tests/unit/declared-size.test.ts`
holds each path, and `jobs-worker.test.ts` the extraction through the real worker.
- **An untrusted package plays as data.** This matches what lets the CMS plugins accept packages
from authors: they install library code from an upload only for a user who may update
libraries, keep `content/` to a list of file types, and filter every field against the
Expand Down
2 changes: 1 addition & 1 deletion packages/player/src/jobs/jobs-worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -399,7 +399,7 @@ async function extractEntry(

const stopReporting = reportRunning(handle, pkgId, entryName)
try {
await inflated(streamSpan(handle, { start, end }), location.method, location.compressedSize).pipeTo(
await inflated(streamSpan(handle, { start, end }), { ...location, name: entryName }).pipeTo(
createChunkWriter({
store,
entry: entryName,
Expand Down
8 changes: 4 additions & 4 deletions packages/player/src/jobs/warm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { WARM_ENTRY, WARM_STALL_MS } from '../shared/constants.js'
import { QuotaError, type ChunkStore } from '../shared/chunk-store.js'
import { DEFLATE, LOCAL_HEADER_FIXED_SIZE, STORED, localHeaderDataStart } from '../shared/local-header.js'
import { contentTypeOf } from '../shared/mime.js'
import type { WarmSpan } from '../shared/protocol.js'
import type { WarmEntry, WarmSpan } from '../shared/protocol.js'
import type { SourceHandle } from '../shared/source.js'

/**
Expand Down Expand Up @@ -58,7 +58,7 @@ export async function warmPackage(
result.skipped += 1
} else {
try {
await store.putWhole(entry.name, () => bodyOf(compressed, entry.method), contentTypeOf(entry.name), entry.size)
await store.putWhole(entry.name, () => bodyOf(compressed, entry), contentTypeOf(entry.name), entry.size)
result.stored += 1
} catch (error) {
// No room is the end of it: the store is full for the rest of the spans too.
Expand Down Expand Up @@ -86,8 +86,8 @@ export async function warmPackage(
return result
}

function bodyOf(compressed: Uint8Array<ArrayBuffer>, method: number): ReadableStream<Uint8Array> {
return inflated(new Blob([compressed]).stream(), method, compressed.length)
function bodyOf(compressed: Uint8Array<ArrayBuffer>, entry: WarmEntry): ReadableStream<Uint8Array> {
return inflated(new Blob([compressed]).stream(), entry)
}

/**
Expand Down
6 changes: 6 additions & 0 deletions packages/player/src/shared/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,12 @@ export const INLINE_MAX_SIZE = 16 * 1024 * 1024
*/
export const MEDIA_INLINE_MAX_SIZE = 1024 * 1024

/**
* The largest JSON entry the Service Worker parses, as parsing holds it whole: a larger one is
* refused unread. Of 89 real packages, the largest `content.json` is 150 kB.
*/
export const PARSED_MAX_SIZE = 16 * 1024 * 1024

/**
* A large span is pulled as ranged requests of this size, `SEGMENT_CONCURRENCY` at once, in order.
* Up to 16 MB is held, a deliberate loosening of one chunk in memory, so 4 MB and not 8.
Expand Down
26 changes: 23 additions & 3 deletions packages/player/src/shared/stream-utils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { STORED } from './local-header.js'
import { PlayerError } from './protocol.js'
import type { ByteRange } from './range.js'

/**
Expand Down Expand Up @@ -67,8 +68,27 @@ export function deferredStream(open: () => Promise<ReadableStream<Uint8Array>>):
* An entry's bytes as stored, inflated when deflated, by the native codec zip.js would use. The lib
* types its input as `BufferSource`, stricter than the views it gets, so the one cast is here.
*/
export function inflated(stored: ReadableStream<Uint8Array>, method: number, compressedSize: number): ReadableStream<Uint8Array> {
if (method === STORED || compressedSize === 0) return stored
export function inflated(
stored: ReadableStream<Uint8Array>,
entry: { name: string; method: number; compressedSize: number; size: number }
): ReadableStream<Uint8Array> {
const held = heldTo(entry.size, entry.name)
if (entry.method === STORED || entry.compressedSize === 0) return stored.pipeThrough(held)
const inflate = new DecompressionStream('deflate-raw') as unknown as ReadableWritablePair<Uint8Array, Uint8Array>
return stored.pipeThrough(inflate)
return stored.pipeThrough(inflate).pipeThrough(held)
}

/**
* Fails a stream that runs past `size`, as zip.js does for what it reads: the native codec knows
* no declared size, and a few MB that inflate without end would fill the store and evict the rest.
*/
function heldTo(size: number, name: string): TransformStream<Uint8Array, Uint8Array> {
let seen = 0
return new TransformStream({
transform(chunk, controller) {
seen += chunk.length
if (seen > size) throw new PlayerError('bad-archive', `${name} is longer than the ${size} bytes its archive declares`)
controller.enqueue(chunk)
}
})
}
3 changes: 1 addition & 2 deletions packages/player/src/sw/mount.ts
Original file line number Diff line number Diff line change
Expand Up @@ -931,8 +931,7 @@ class VirtualServer {

/** An entry's JSON, from the cache when it is there, as every library's is after the warm. */
private async readJson({ reader, entry }: LocatedEntry): Promise<unknown> {
const cached = await new ChunkStore(reader.pkgId).getWhole(entry.name)
return (cached ?? new Response(reader.inflate(entry))).json()
return reader.json(entry, await new ChunkStore(reader.pkgId).getWhole(entry.name))
}

/** Asks the page for a `File` the worker lost on restart, and waits for it to arrive. */
Expand Down
32 changes: 27 additions & 5 deletions packages/player/src/sw/package-reader.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { ZipReader, type Entry, type FileEntry } from '@zip.js/zip.js'
import { BLOCK_CACHE_MAX_READ, INLINE_MAX_SIZE, MEDIA_INLINE_MAX_SIZE, WARM_ENTRY_MAX_SIZE, WARM_GAP, WARM_MAX_BYTES } from '../shared/constants.js'
import { BLOCK_CACHE_MAX_READ, INLINE_MAX_SIZE, MEDIA_INLINE_MAX_SIZE, PARSED_MAX_SIZE, WARM_ENTRY_MAX_SIZE, WARM_GAP, WARM_MAX_BYTES } from '../shared/constants.js'
import { indexEntryNames, normalizeEntryName } from '../shared/entry-names.js'
import { extensionOf, isMediaEntry, isTextEntry } from '../shared/mime.js'
import { DEFLATE, LOCAL_HEADER_FIXED_SIZE, STORED, readDataStart } from '../shared/local-header.js'
Expand Down Expand Up @@ -681,7 +681,7 @@ export class PackageReader {
if (this.contentJson) return this.contentJson
const located = this.locate('content/content.json')
if (!located || located.reader !== this) return Promise.resolve(undefined)
this.contentJson = new Response(this.inflate(located.entry)).json().catch(() => undefined)
this.contentJson = this.json(located.entry).catch(() => undefined)
return this.contentJson
}

Expand All @@ -703,7 +703,7 @@ export class PackageReader {
const newest = folders.reduce((a, b) => (b.major > a.major || (b.major === a.major && b.minor > a.minor) ? b : a))
const entry = this.entries.get(`${newest.folder}/library.json`)
if (!entry) continue
const patterns = addonPatterns(await new Response(this.inflate(entry)).json().catch(() => null))
const patterns = addonPatterns(await this.json(entry).catch(() => null))
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
if (patterns.length > 0) addons.push({ machineName, majorVersion: newest.major, minorVersion: newest.minor, patterns })
}
return addons
Expand Down Expand Up @@ -796,6 +796,18 @@ export class PackageReader {
return kept
}

/**
* An entry parsed as JSON, from the `cached` copy when there is one. Parsing holds it whole, so
* one over `PARSED_MAX_SIZE` is refused unread: a few kB can inflate to gigabytes.
*/
async json(entry: IndexedEntry, cached?: Response): Promise<unknown> {
const bytes = parsedSize(entry)
if (bytes > PARSED_MAX_SIZE) {
throw new PlayerError('bad-archive', `${entry.name} is ${bytes} bytes, and the player reads a JSON file of at most ${PARSED_MAX_SIZE}`)
}
return (cached ?? new Response(this.inflate(entry))).json()
}

/**
* Inflates an entry into a stream for `cache.put()` or a `Response`, so it is never whole in
* memory. A forward entry has no zip.js object behind it, so `DecompressionStream` inflates it.
Expand Down Expand Up @@ -871,7 +883,7 @@ export class PackageReader {
if (entry.compressedSize === 0) return new Blob([]).stream()

const raw = deferredStream(() => this.sliceStream(entry, { start: 0, end: entry.compressedSize - 1 }))
return inflated(raw, entry.method, entry.compressedSize)
return inflated(raw, entry)
}

private async readDataRange(entry: IndexedEntry): Promise<ByteRange> {
Expand Down Expand Up @@ -949,15 +961,25 @@ function topFolderOf(name: string): string | null {
return slash < 0 ? null : name.slice(0, slash)
}

/**
* What parsing an entry could hold: the larger of what it declares and what the archive carries for
* it, as a stored entry that understates itself has its bytes in the archive all the same.
*/
function parsedSize(entry: IndexedEntry): number {
return Math.max(entry.size, entry.compressedSize)
}

/** `h5p.json` parsed; an unreadable one, or one that is not an object, is a `bad-archive` error. */
async function readManifest(reader: PackageReader): Promise<PackageManifest> {
const { entry } = reader.get('h5p.json')!

try {
const parsed = (await new Response(reader.inflate(entry)).json()) as PackageManifest
const parsed = (await reader.json(entry)) as PackageManifest
if (!parsed || typeof parsed !== 'object') throw new Error('not an object')
return parsed
} catch (error) {
// One refused for its size says so itself.
if (error instanceof PlayerError && parsedSize(entry) > PARSED_MAX_SIZE) throw error
throw new PlayerError('bad-archive', 'h5p.json is not readable JSON', { cause: error })
}
}
Expand Down
24 changes: 23 additions & 1 deletion packages/player/tests/browser/jobs-worker.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { FIXTURES } from './utils'
import { afterAll, describe, expect, it } from 'vitest'
import jobsWorkerSource from 'virtual:h5p-jobs-worker'
import { cacheNameFor } from '../../src/shared/chunk-store'
import { ChunkStore, cacheNameFor } from '../../src/shared/chunk-store'
import type { EntryLocation, FromJobsMessage, SourceDescriptor, ToJobsMessage } from '../../src/shared/protocol'
import { openSource } from '../../src/shared/source'
import { PackageReader, locationOf } from '../../src/sw/package-reader'
Expand Down Expand Up @@ -134,6 +134,28 @@ describe('the Jobs worker', () => {
}
})

it('fails an entry that inflates past the size its archive declares, and keeps none of it', { timeout: 30_000 }, async () => {
const pkgId = 'jobs-worker-declared-size-test'
await caches.delete(cacheNameFor(pkgId))
const packaged = await rangeSource(FIXTURES.largeDeflated)
const big = 'content/media/big.bin'
const { [big]: location } = await locate(pkgId, packaged, [big])
const jobs = spawn()
try {
const ended = jobs.next((message) => message.pkgId === pkgId && message.type !== 'progress')
// What the server would say of an archive whose index understates the entry.
jobs.post({ type: 'extract', pkgId, entry: big, location: { ...location, size: 1024 * 1024 }, source: packaged })

expect(await ended).toMatchObject({ type: 'failed', entry: big, code: 'bad-archive', message: expect.stringContaining(big) })
const store = new ChunkStore(pkgId)
expect(await store.getMeta(big)).toMatchObject({ available: 0, complete: false, error: { code: 'bad-archive' } })
expect(await store.getChunk(big, 0)).toBeUndefined()
} finally {
jobs.dispose()
await caches.delete(cacheNameFor(pkgId))
}
})

it('stores a picked File whole when asked to download it, for a Service Worker that cannot read it (#309)', async () => {
const pkgId = 'jobs-worker-file-copy-test'
await caches.delete(cacheNameFor(pkgId))
Expand Down
Loading