diff --git a/.claude/tasks/contracts/2026-10-13-rust-r0-verify.md b/.claude/tasks/contracts/2026-10-13-rust-r0-verify.md index 49171360..498639fe 100644 --- a/.claude/tasks/contracts/2026-10-13-rust-r0-verify.md +++ b/.claude/tasks/contracts/2026-10-13-rust-r0-verify.md @@ -1,6 +1,6 @@ # CONTRACT — Rust R0 foundation (whole phase, for the fresh verifier) - date: 2026-10-13 | flow: ad-hoc phase (owner go 2026-10-12, BDR-045) | branch: feature/rust-r0-foundation (base develop = 5fec065) -- status: active (amended 2026-10-13 after verifier pass 1: criteria 10 and 14 oracles counted comment lines; CHECKs tightened, no code change) +- status: active (amended 2026-10-13 after verifier pass 1: criteria 10 and 14 oracles counted comment lines; pass 2 CONFORME 16/16, criterion 16 oracle excludes the contract file itself; no code change) - spec: docs/development/RUST_ARCHITECTURE_REVIEW.md (Part III, Annex B, Annex C), docs/development/RUST.md (what was built and proven) - evidence logs (runs made by the orchestrator on this host, readable): /tmp/claude-1000/-home-bchanot-Documents-faunosteo/2fbc125b-9811-4458-8ebc-489c2f9255be/scratchpad/{pnpm-check.log,worker-test-build-5.log,worker-image-build-2.log,builder-build-2.log} @@ -54,5 +54,5 @@ Implement R0 per Annex B: Cargo workspace with crates core, wasm, worker; pinned CHECK: grep -c "^### 5\.[1-7]" docs/development/RUST.md; grep -c "^## 7. What stays hypothetical" docs/development/RUST.md; grep -c "^## Image deploy by digest (prepared at R0, not yet applied)" DEPLOY.md; grep -c "docker compose up --build -d" DEPLOY.md; grep -c "wasm-unsafe-eval" DEPLOY.md; grep -c "pnpm rust:check" CLAUDE.md; grep -c "crates/worker" docs/development/WORKSPACE.md; grep -c "Worker sandbox" docs/development/TEST_STRATEGY.md; grep -c "core-wasm" packages/README.md; grep -c "Rust foundation, plan R0" CHANGELOG.md EXPECT: 7 ; 1 ; 1 ; >= 2 (live procedure kept) ; >= 2 ; >= 1 ; >= 1 ; 1 ; >= 1 ; 1 16. No secret and no credential in the new files; the worker's env check and the CI secrets usage are the only places naming keys. - CHECK: git diff 5fec065..HEAD | grep -E "^\+" | grep -Ei "eyJ[a-zA-Z0-9_-]{20,}|sk_live|service_role_key *= *\"[^\"]+\"|password *= *\"" | wc -l; grep -c "secrets.REGISTRY_TOKEN" .gitea/workflows/release-images.yml + CHECK: git diff 5fec065..HEAD -- . ':!.claude/tasks/contracts' | grep -E "^\+" | grep -Ei "eyJ[a-zA-Z0-9_-]{20,}|sk_live|service_role_key *= *\"[^\"]+\"|password *= *\"" | wc -l; grep -c "secrets.REGISTRY_TOKEN" .gitea/workflows/release-images.yml EXPECT: 0 ; 1 diff --git a/.gitea/workflows/release-images.yml b/.gitea/workflows/release-images.yml index 88099ecb..a6062de7 100644 --- a/.gitea/workflows/release-images.yml +++ b/.gitea/workflows/release-images.yml @@ -4,13 +4,17 @@ # a validation. Nothing here deploys; DEPLOY.md "Image deploy by digest (prepared at R0, not # yet applied)" is the runbook. # -# Hardening (security audit of R0): the dispatch input is a typed choice re-validated in -# the shell through an environment variable (never interpolated into a script); secrets -# reach the shell through env only, the registry login lives in a per-job DOCKER_CONFIG -# removed at the end; images are built by an ephemeral buildx builder with its own cache, -# so nothing a PR build left in the daemon's cache mounts or volumes can reach a release -# image; the RustSec advisories gate runs before any push; only main and develop may be -# released; the checkout action is pinned to a commit. +# Hardening (security audits of R0): the dispatch input is a typed choice re-validated in +# the shell through an environment variable (never interpolated into a script); the registry +# token reaches the login step only, through env, into a per-job DOCKER_CONFIG under +# RUNNER_TEMP created before any step and removed by a literal path; the images are built by +# a named ephemeral buildx builder (`--builder`, so a missing builder fails instead of +# falling back to the daemon's shared BuildKit and its cache mounts); the RustSec and npm +# advisories gates run before any push; `actions/checkout` is pinned to a commit. The +# `if: github.ref` line keeps honest runs on main or develop: it is not a security boundary +# (whoever can push a branch can dispatch a copy of this file), push access and the token's +# scope are. The real isolation from pull-request jobs is a dedicated release runner label +# that never runs them (Step 27 operations). # # Secrets expected on the forge: REGISTRY (host, e.g. the Gitea container registry of this # forge), REGISTRY_USER, REGISTRY_TOKEN (write:package scope). Images are pushed as @@ -37,11 +41,14 @@ jobs: env: SHEET_BUNDLE: ${{ inputs.sheet_bundle }} REGISTRY: ${{ secrets.REGISTRY }} - REGISTRY_USER: ${{ secrets.REGISTRY_USER }} - REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }} NAMESPACE: ${{ github.repository_owner }} GIT_SHA: ${{ github.sha }} + # Per-job Docker config, set before any step runs: the login and the builder live here. + DOCKER_CONFIG: ${{ runner.temp }}/faunosteo-release-docker + BUILDER: faunosteo_release_${{ github.sha }} steps: + - name: Per-job Docker config directory + run: mkdir -m 700 -p "$DOCKER_CONFIG" - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - name: Validate the dispatch input (the shell trusts the env value only after this) run: | @@ -53,25 +60,40 @@ jobs: run: | docker build -f docker/rust-builder.Dockerfile -t faunosteo_rust_builder:1.99.0 docker bash docker/rust-run.sh cargo deny check advisories - - name: Ephemeral builder with its own cache and a per-job Docker config + - uses: actions/setup-node@v4 + with: + node-version-file: .nvmrc + - name: npm advisories gate for the application image (production dependencies) run: | - echo "DOCKER_CONFIG=$(mktemp -d)" >> "$GITHUB_ENV" - docker buildx create --name "faunosteo_release_$GIT_SHA" --driver docker-container --use - - name: Registry login (token from env, never on the command line) + corepack enable && corepack prepare --activate + pnpm install --frozen-lockfile + pnpm audit --prod --audit-level=high + - name: Ephemeral builder with its own cache (named; every build names it explicitly) + run: docker buildx create --name "$BUILDER" --driver docker-container + - name: Registry login (token in this step's env only, never on the command line) + env: + REGISTRY_USER: ${{ secrets.REGISTRY_USER }} + REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }} run: printf '%s' "$REGISTRY_TOKEN" | docker login "$REGISTRY" -u "$REGISTRY_USER" --password-stdin - name: Build and push the application image run: | image="$REGISTRY/$NAMESPACE/faunosteo_app:$GIT_SHA" - docker buildx build --push --provenance=false --build-arg "SHEET_BUNDLE=$SHEET_BUNDLE" -t "$image" . - echo "app: $(docker buildx imagetools inspect "$image" --format '{{json .Manifest.Digest}}')" >> "$GITHUB_STEP_SUMMARY" + docker buildx build --builder "$BUILDER" --push --provenance=false \ + --metadata-file "$RUNNER_TEMP/app-metadata.json" \ + --build-arg "SHEET_BUNDLE=$SHEET_BUNDLE" -t "$image" . + digest="$(sed -n 's/.*"containerimage.digest": *"\([^"]*\)".*/\1/p' "$RUNNER_TEMP/app-metadata.json")" + echo "app: $image@$digest" >> "$GITHUB_STEP_SUMMARY" - name: Build and push the worker image run: | image="$REGISTRY/$NAMESPACE/faunosteo_worker:$GIT_SHA" - docker buildx build --push --provenance=false -f crates/worker/Dockerfile -t "$image" . - echo "worker: $(docker buildx imagetools inspect "$image" --format '{{json .Manifest.Digest}}')" >> "$GITHUB_STEP_SUMMARY" - - name: Logout, remove the builder and the per-job Docker config + docker buildx build --builder "$BUILDER" --push --provenance=false \ + --metadata-file "$RUNNER_TEMP/worker-metadata.json" \ + -f crates/worker/Dockerfile -t "$image" . + digest="$(sed -n 's/.*"containerimage.digest": *"\([^"]*\)".*/\1/p' "$RUNNER_TEMP/worker-metadata.json")" + echo "worker: $image@$digest" >> "$GITHUB_STEP_SUMMARY" + - name: Logout, remove the builder and the per-job Docker config (literal path) if: always() run: | docker logout "$REGISTRY" || true - docker buildx rm "faunosteo_release_$GIT_SHA" || true - rm -rf "$DOCKER_CONFIG" + docker buildx rm "$BUILDER" + rm -rf -- "${RUNNER_TEMP:?}/faunosteo-release-docker" diff --git a/Cargo.lock b/Cargo.lock index c6f058b1..71145926 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -93,6 +93,7 @@ name = "faunosteo-worker" version = "0.1.0" dependencies = [ "crc32fast", + "flate2", "image", "libc", "libwebp-sys", diff --git a/crates/worker/Cargo.toml b/crates/worker/Cargo.toml index dc9fda62..d74f8a80 100644 --- a/crates/worker/Cargo.toml +++ b/crates/worker/Cargo.toml @@ -18,7 +18,7 @@ path = "src/main.rs" default = [] # Extra subcommands and flags for the sandbox tests and the seccomp derivation # (crates/worker/Dockerfile stage `test`); never part of a release build. -test-hooks = ["dep:crc32fast"] +test-hooks = ["dep:crc32fast", "dep:flate2"] [dependencies] image.workspace = true @@ -27,6 +27,8 @@ seccompiler.workspace = true rlimit.workspace = true libc.workspace = true crc32fast = { version = "1.4", optional = true } +# Already in the tree through png: used by the iCCP-bomb fixture only. +flate2 = { version = "1.1", optional = true } # The worker owns I/O (it is the process boundary), so the core's disallowed_methods lint is # off here. unsafe stays denied crate-wide; the libwebp FFI and the prctl call carry a local diff --git a/crates/worker/Dockerfile b/crates/worker/Dockerfile index 6f3b4fd0..dffcd4bf 100644 --- a/crates/worker/Dockerfile +++ b/crates/worker/Dockerfile @@ -24,11 +24,12 @@ RUN --mount=type=cache,id=faunosteo_cargo_registry_musl,target=/usr/local/cargo/ # by it): the binary under test differs from the shipped one by the feature-gated hooks only. FROM base AS test RUN apk add --no-cache strace +# Own target cache: the hooks build and the shipped build must never share target/release. RUN --mount=type=cache,id=faunosteo_cargo_registry_musl,target=/usr/local/cargo/registry \ - --mount=type=cache,id=faunosteo_target_musl,target=/w/target \ + --mount=type=cache,id=faunosteo_target_musl_test,target=/w/target \ cargo test -p faunosteo-worker --release --features test-hooks --locked -- --test-threads=4 RUN --mount=type=cache,id=faunosteo_cargo_registry_musl,target=/usr/local/cargo/registry \ - --mount=type=cache,id=faunosteo_target_musl,target=/w/target \ + --mount=type=cache,id=faunosteo_target_musl_test,target=/w/target \ sh crates/worker/scripts/derive-seccomp.sh FROM gcr.io/distroless/static-debian12:nonroot AS runtime diff --git a/crates/worker/src/decode.rs b/crates/worker/src/decode.rs index 3f7b1255..44d9adcb 100644 --- a/crates/worker/src/decode.rs +++ b/crates/worker/src/decode.rs @@ -21,7 +21,11 @@ pub enum Reject { UnsupportedType, DecodeFailed, Dimensions, + /// A decoder budget (`image::Limits`, allocation, complexity) exceeded by the content. + ResourceLimit, + /// libwebp failed on the buffer the child produced itself: an environment fault. EncodeFailed, + /// A programming or I/O fault of the child, never a judgement on the content. Internal, } @@ -31,6 +35,7 @@ impl Reject { Self::UnsupportedType => exit_codes::UNSUPPORTED_TYPE, Self::DecodeFailed => exit_codes::DECODE_FAILED, Self::Dimensions => exit_codes::DIMENSIONS, + Self::ResourceLimit => exit_codes::RESOURCE_LIMIT, Self::EncodeFailed => exit_codes::ENCODE_FAILED, Self::Internal => exit_codes::INTERNAL, } @@ -120,15 +125,16 @@ pub fn process(bytes: &[u8]) -> Result, Reject> { encode_webp(square.as_raw(), OUTPUT_SIDE, OUTPUT_SIDE, WEBP_QUALITY) } +/// Every decode-time error is a judgement on the content (a content code): an uploader must +/// never be able to produce a "broken environment" outcome (security audit of R0). fn map_image_error(error: ImageError) -> Reject { match error { ImageError::Limits(limit) => match limit.kind() { LimitErrorKind::DimensionError => Reject::Dimensions, - _ => Reject::Internal, + _ => Reject::ResourceLimit, }, ImageError::Unsupported(_) => Reject::UnsupportedType, - ImageError::Decoding(_) | ImageError::IoError(_) => Reject::DecodeFailed, - _ => Reject::Internal, + _ => Reject::DecodeFailed, } } @@ -149,7 +155,7 @@ pub fn encode_webp(rgba: &[u8], width: u32, height: u32, quality: f32) -> Result return Err(Reject::Internal); }; let mut output: *mut u8 = std::ptr::null_mut(); - // SAFETY: `rgba` holds exactly width × height × 4 bytes (checked above) with the matching + // SAFETY [gated 2026-10-13]: `rgba` holds exactly width × height × 4 bytes (checked above) with the matching // stride; libwebp allocates the encoded buffer, writes its address into `output` and // returns its size. The buffer is copied once and released with the matching WebPFree. let size = @@ -167,7 +173,7 @@ pub fn encode_webp(rgba: &[u8], width: u32, height: u32, quality: f32) -> Result /// Version of the libwebp linked into this binary, as (major, minor, revision). #[allow(unsafe_code)] pub fn libwebp_version() -> (u8, u8, u8) { - // SAFETY: a pure getter of the FFI without arguments or side effects. + // SAFETY [gated 2026-10-13]: a pure getter of the FFI without arguments or side effects. let packed = unsafe { libwebp_sys::WebPGetEncoderVersion() }; let packed = u32::try_from(packed).unwrap_or(0); ( @@ -196,6 +202,10 @@ enum HookAction { AllocGib(usize), /// Burns CPU forever: `RLIMIT_CPU` (SIGXCPU) or the parent's deadline must stop it. Spin, + /// Sends SIGTERM to the parent through `tkill`: the argument filter must kill the child. + SignalParent, + /// Maps executable memory: the `mmap` argument filter must kill the child. + MmapExec, } impl TestHooks { @@ -216,6 +226,8 @@ impl TestHooks { "--violate" => hooks.action = Some(HookAction::Violate), "--flood" => hooks.action = Some(HookAction::Flood), "--spin" => hooks.action = Some(HookAction::Spin), + "--signal-parent" => hooks.action = Some(HookAction::SignalParent), + "--mmap-exec" => hooks.action = Some(HookAction::MmapExec), "--alloc-gib" => { let value = iter .next() @@ -272,6 +284,22 @@ impl TestHooks { HookAction::Spin => loop { std::hint::black_box(0u8); }, + HookAction::SignalParent => { + let survived = negative_hooks::signal_parent(); + let _ = writeln!( + stderr, + "decode: tkill(parent) survived the filter: {survived}" + ); + Some(exit_codes::INTERNAL) + } + HookAction::MmapExec => { + let survived = negative_hooks::mmap_exec(); + let _ = writeln!( + stderr, + "decode: mmap(PROT_EXEC) survived the filter: {survived}" + ); + Some(exit_codes::INTERNAL) + } } } @@ -281,6 +309,36 @@ impl TestHooks { } } +/// Negative proofs of the seccomp argument filters (`test-hooks` only): each call must die +/// with SIGSYS before returning; a return value means the filter let it through. +#[cfg(feature = "test-hooks")] +#[allow(unsafe_code)] +mod negative_hooks { + /// `tkill(getppid(), SIGTERM)`: a signal to another process. + pub fn signal_parent() -> i32 { + // SAFETY [gated 2026-10-13]: integer arguments only; the syscall is expected to be + // refused by the filter (KillProcess) and never to reach the parent. + unsafe { libc::syscall(libc::SYS_tkill, libc::getppid(), libc::SIGTERM) as i32 } + } + + /// `mmap` of one executable page. + pub fn mmap_exec() -> i32 { + // SAFETY [gated 2026-10-13]: an anonymous private mapping with no file and a null + // hint; the filter is expected to kill the process before it exists. + let page = unsafe { + libc::mmap( + std::ptr::null_mut(), + 4096, + libc::PROT_READ | libc::PROT_EXEC, + libc::MAP_PRIVATE | libc::MAP_ANONYMOUS, + -1, + 0, + ) + }; + i32::from(page != libc::MAP_FAILED) + } +} + /// Reads at most `cap` bytes from a reader, reporting whether more were available. pub fn read_capped(reader: &mut dyn Read, cap: usize) -> io::Result<(Vec, bool)> { let mut buffer = Vec::new(); diff --git a/crates/worker/src/exit_codes.rs b/crates/worker/src/exit_codes.rs index 570f659d..f787e494 100644 --- a/crates/worker/src/exit_codes.rs +++ b/crates/worker/src/exit_codes.rs @@ -13,11 +13,18 @@ pub const DIMENSIONS: i32 = 15; pub const ENCODE_FAILED: i32 = 16; pub const OUTPUT_FAILED: i32 = 17; pub const INTERNAL: i32 = 18; +/// The decoders' allocation or complexity budget was exceeded by the content. +pub const RESOURCE_LIMIT: i32 = 19; -/// Codes that judge the content (the upload is refused); every other non-zero code means -/// the child's environment is broken and the parent must alert rather than reject. +/// Codes that judge the content (the upload is refused). Every other non-zero code means +/// the child's environment is broken (`Broken` outcome: the parent alerts rather than +/// rejects). Explicit list on purpose: a new code never lands in the wrong class by +/// accident, and no content can produce a "broken" code. pub fn is_content_rejection(code: i32) -> bool { - (INPUT_TOO_LARGE..=OUTPUT_FAILED).contains(&code) + matches!( + code, + INPUT_TOO_LARGE | UNSUPPORTED_TYPE | DECODE_FAILED | DIMENSIONS | RESOURCE_LIMIT + ) } /// Stable name of an exit code for logs and tests. @@ -34,6 +41,7 @@ pub fn name(code: i32) -> &'static str { ENCODE_FAILED => "encode_failed", OUTPUT_FAILED => "output_failed", INTERNAL => "internal", + RESOURCE_LIMIT => "resource_limit", _ => "unknown", } } diff --git a/crates/worker/src/fixtures.rs b/crates/worker/src/fixtures.rs index de6149ca..d806e7a5 100644 --- a/crates/worker/src/fixtures.rs +++ b/crates/worker/src/fixtures.rs @@ -62,6 +62,34 @@ fn push_chunk(out: &mut Vec, kind: &[u8; 4], payload: &[u8]) { out.extend_from_slice(&hasher.finalize().to_be_bytes()); } +/// A small valid-looking PNG whose `iCCP` profile inflates to `inflated_bytes` (hundreds of +/// kilobytes of compressed zeros): the decoder's allocation budget must refuse it as content +/// (`resource_limit`), never as a broken environment. +pub fn png_iccp_bomb(inflated_bytes: usize) -> Vec { + use std::io::Write; + let mut out = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a]; + let mut ihdr = Vec::new(); + ihdr.extend_from_slice(&64u32.to_be_bytes()); + ihdr.extend_from_slice(&64u32.to_be_bytes()); + ihdr.extend_from_slice(&[8, 6, 0, 0, 0]); + push_chunk(&mut out, b"IHDR", &ihdr); + let mut iccp = b"p\0\0".to_vec(); + let mut encoder = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::best()); + let zeros = vec![0u8; 1 << 20]; + let mut written = 0; + while written < inflated_bytes { + let chunk = (inflated_bytes - written).min(zeros.len()); + if encoder.write_all(&zeros[..chunk]).is_err() { + break; + } + written += chunk; + } + iccp.extend_from_slice(&encoder.finish().unwrap_or_default()); + push_chunk(&mut out, b"iCCP", &iccp); + push_chunk(&mut out, b"IEND", &[]); + out +} + /// The first bytes of a GIF: a format the avatar pipeline never accepts. pub fn gif() -> Vec { let mut out = b"GIF89a".to_vec(); @@ -89,6 +117,7 @@ pub fn by_name(name: &str) -> Option> { "big-png" => png(3000, 3000), "tiny" => png(32, 32), "huge-header" => png_header_only(20_000, 20_000), + "iccp-bomb" => png_iccp_bomb(300 << 20), "gif" => gif(), "truncated" => truncated_png(), _ => return None, diff --git a/crates/worker/src/sandbox.rs b/crates/worker/src/sandbox.rs index 44f080cf..d995da4f 100644 --- a/crates/worker/src/sandbox.rs +++ b/crates/worker/src/sandbox.rs @@ -100,11 +100,18 @@ pub fn apply(limits: &Limits, seccomp: bool) -> Result<(), SandboxError> { /// `PR_SET_DUMPABLE 0` is the kernel-side stop, `RLIMIT_CORE 0` the belt. #[allow(unsafe_code)] fn disable_core_dumps() -> Result<(), SandboxError> { - // SAFETY: prctl(PR_SET_DUMPABLE, 0) takes no pointer and changes only this process. + // SAFETY [gated 2026-10-13]: prctl with integer arguments only, changes this process only. let rc = unsafe { libc::prctl(libc::PR_SET_DUMPABLE, 0, 0, 0, 0) }; if rc != 0 { return Err(SandboxError::Rlimit("PR_SET_DUMPABLE".to_owned())); } + // SAFETY [gated 2026-10-13]: a getter with integer arguments. + let dumpable = unsafe { libc::prctl(libc::PR_GET_DUMPABLE, 0, 0, 0, 0) }; + if dumpable != 0 { + return Err(SandboxError::Rlimit(format!( + "PR_GET_DUMPABLE = {dumpable}" + ))); + } rlimit::setrlimit(rlimit::Resource::CORE, 0, 0) .map_err(|error| SandboxError::Rlimit(format!("RLIMIT_CORE: {error}"))) } diff --git a/crates/worker/src/spawn.rs b/crates/worker/src/spawn.rs index 3cde1f12..bf9d068f 100644 --- a/crates/worker/src/spawn.rs +++ b/crates/worker/src/spawn.rs @@ -17,11 +17,13 @@ use crate::{exit_codes, webp_check}; pub enum ChildOutcome { /// A 512 × 512 WebP whose container passed the parent's check. Produced(Vec), - /// The child refused the input with one of its content exit codes (12 to 17). + /// The child refused the input with one of its content exit codes + /// (`exit_codes::is_content_rejection`). Rejected { code: i32, name: &'static str }, - /// The child could not even start properly (usage, non-empty environment, sandbox - /// failure, internal error): the confinement environment is broken, not the upload. - /// R1 alerts and stops on this outcome instead of rejecting the job. + /// The child could not run properly (usage, non-empty environment, sandbox failure, + /// encode or output failure, internal error): the confinement environment is broken, + /// not the upload. No content can produce this outcome (every decode-time error maps + /// to a content code). R1 alerts and stops on it instead of rejecting the job. Broken { code: i32, name: &'static str }, /// The child died from a signal (SIGSYS 31 = seccomp, SIGABRT 6 = allocation failure, /// SIGXCPU 24 = CPU limit, SIGKILL 9 = the parent). diff --git a/crates/worker/src/webp_check.rs b/crates/worker/src/webp_check.rs index 0fc9457e..7af7ec10 100644 --- a/crates/worker/src/webp_check.rs +++ b/crates/worker/src/webp_check.rs @@ -55,8 +55,9 @@ pub fn inspect(bytes: &[u8]) -> Result { } let mut offset = 12; - let mut chunks = Vec::new(); - let mut dimensions = None; + let mut chunks: Vec<[u8; 4]> = Vec::new(); + let mut canvas: Option<(u32, u32)> = None; + let mut frame: Option<(u32, u32)> = None; while offset < bytes.len() { let chunk_header = bytes .get(offset..offset + 8) @@ -79,25 +80,43 @@ pub fn inspect(bytes: &[u8]) -> Result { if !ALLOWED_CHUNKS.contains(&&fourcc) { return Err(WebpIssue::ForbiddenChunk(fourcc)); } - let declared = match &fourcc { - b"VP8X" => Some(parse_vp8x(payload)?), - b"VP8 " => Some(parse_vp8(payload)?), - b"VP8L" => Some(parse_vp8l(payload)?), - _ => None, - }; - // The canvas (VP8X) and the frame (VP8 / VP8L) must agree: a container whose frame - // disagrees with its canvas is not something the encoder produces. - match (dimensions, declared) { - (None, Some(size)) => dimensions = Some(size), - (Some(canvas), Some(frame)) if canvas != frame => { - return Err(WebpIssue::BadBitstream); + // Structure the encoder produces, and nothing else: an optional VP8X first, then an + // optional ALPH (extended files only), then exactly one VP8 or VP8L frame. + match &fourcc { + b"VP8X" => { + if !chunks.is_empty() { + return Err(WebpIssue::BadBitstream); + } + canvas = Some(parse_vp8x(payload)?); } - _ => {} + b"ALPH" => { + if canvas.is_none() || frame.is_some() { + return Err(WebpIssue::BadBitstream); + } + } + b"VP8 " | b"VP8L" => { + if frame.is_some() { + return Err(WebpIssue::BadBitstream); + } + frame = Some(if &fourcc == b"VP8 " { + parse_vp8(payload)? + } else { + parse_vp8l(payload)? + }); + } + _ => return Err(WebpIssue::ForbiddenChunk(fourcc)), } chunks.push(fourcc); offset = end + (size & 1); } - let (width, height) = dimensions.ok_or(WebpIssue::MissingBitstream)?; + let frame = frame.ok_or(WebpIssue::MissingBitstream)?; + // The canvas (VP8X) and the frame must agree: the encoder never writes otherwise. + if let Some(canvas) = canvas + && canvas != frame + { + return Err(WebpIssue::BadBitstream); + } + let (width, height) = canvas.unwrap_or(frame); Ok(WebpSummary { width, height, @@ -190,15 +209,55 @@ mod tests { assert_eq!(inspect(&bytes), Err(WebpIssue::BadBitstream)); } + #[test] + fn chunk_structure_is_strict() { + let mut vp8 = vec![0u8; 20]; + vp8[3..6].copy_from_slice(&[0x9d, 0x01, 0x2a]); + vp8[6..8].copy_from_slice(&512u16.to_le_bytes()); + vp8[8..10].copy_from_slice(&512u16.to_le_bytes()); + // two frames + assert_eq!( + inspect(&riff(&[(b"VP8 ", &vp8), (b"VP8 ", &vp8)])), + Err(WebpIssue::BadBitstream) + ); + // ALPH without VP8X + assert_eq!( + inspect(&riff(&[(b"ALPH", &[0; 4]), (b"VP8 ", &vp8)])), + Err(WebpIssue::BadBitstream) + ); + // VP8X not first + assert_eq!( + inspect(&riff(&[(b"VP8 ", &vp8), (b"VP8X", &vp8x(512, 512))])), + Err(WebpIssue::BadBitstream) + ); + // the encoder's extended layout + assert!( + expect_square( + &riff(&[ + (b"VP8X", &vp8x(512, 512)), + (b"ALPH", &[0; 4]), + (b"VP8 ", &vp8) + ]), + 512 + ) + .is_ok() + ); + } + #[test] fn metadata_chunks_are_refused() { let bytes = riff(&[(b"VP8X", &vp8x(512, 512)), (b"EXIF", b"x")]); + // refused on the chunk type before any structural rule assert_eq!(inspect(&bytes), Err(WebpIssue::ForbiddenChunk(*b"EXIF"))); } #[test] fn wrong_sizes_are_refused() { - let bytes = riff(&[(b"VP8X", &vp8x(511, 512))]); + let mut vp8 = vec![0u8; 20]; + vp8[3..6].copy_from_slice(&[0x9d, 0x01, 0x2a]); + vp8[6..8].copy_from_slice(&511u16.to_le_bytes()); + vp8[8..10].copy_from_slice(&512u16.to_le_bytes()); + let bytes = riff(&[(b"VP8X", &vp8x(511, 512)), (b"VP8 ", &vp8)]); assert_eq!( expect_square(&bytes, 512), Err(WebpIssue::Dimensions { @@ -209,6 +268,10 @@ mod tests { let mut truncated = riff(&[(b"VP8X", &vp8x(512, 512))]); truncated.pop(); assert_eq!(inspect(&truncated), Err(WebpIssue::RiffSizeMismatch)); + assert_eq!( + inspect(&riff(&[(b"VP8X", &vp8x(512, 512))])), + Err(WebpIssue::MissingBitstream) + ); assert_eq!(inspect(b"not a webp"), Err(WebpIssue::TooShort)); } diff --git a/crates/worker/tests/sandbox.rs b/crates/worker/tests/sandbox.rs index 3b0ed8ff..7c7910a5 100644 --- a/crates/worker/tests/sandbox.rs +++ b/crates/worker/tests/sandbox.rs @@ -84,6 +84,36 @@ fn oversized_headers_are_refused_before_decoding() { ); } +#[test] +fn an_iccp_bomb_is_a_content_rejection_not_a_broken_environment() { + expect_rejected( + &fixtures::png_iccp_bomb(300 << 20), + exit_codes::RESOURCE_LIMIT, + ); +} + +#[test] +fn a_signal_to_the_parent_is_killed_by_the_argument_filter() { + let run = with_hook(&["--signal-parent"]).decode(b""); + assert!( + matches!(run.outcome, ChildOutcome::Signalled { signal: SIGSYS }), + "{:?} {}", + run.outcome, + run.stderr + ); +} + +#[test] +fn an_executable_mapping_is_killed_by_the_argument_filter() { + let run = with_hook(&["--mmap-exec"]).decode(b""); + assert!( + matches!(run.outcome, ChildOutcome::Signalled { signal: SIGSYS }), + "{:?} {}", + run.outcome, + run.stderr + ); +} + #[test] fn unsupported_formats_are_refused() { expect_rejected(&fixtures::gif(), exit_codes::UNSUPPORTED_TYPE);