diff --git a/AGENTS.md b/AGENTS.md index 41af33a..06fe473 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -14,7 +14,7 @@ scanning, application execution, image decoding or exploit payloads. ## Project map - `sharp_rsvg_rce_check.py`: generated, standalone Python 3.10+ executable. -- `src/checker.py`, `vendor/common.py`: product logic and vendored evidence/report helpers. +- `src/checker.py`, `src/adapters.py`, `vendor/common.py`: product logic and vendored evidence/report helpers. - `rules/snapshot.json`: dated, source-linked enabled rule snapshot. - `tools/build.py`: deterministic single-file build and release checksums. - `test_assessment.py`, `test_contract.py`: synthetic offline behavior tests. diff --git a/README.md b/README.md index 8455d7d..7a97fbf 100644 --- a/README.md +++ b/README.md @@ -68,7 +68,7 @@ python sharp_rsvg_rce_check.py --help git diff --check ``` -Tests use synthetic local fixtures. CI is configured for Python 3.10 and 3.14 on Linux, Windows and macOS; assess its result for the exact published commit separately from local verification. Edit `src/checker.py`, `vendor/common.py` or `rules/snapshot.json`, then rebuild with `python tools/build.py`. The generated checker has no runtime dependency on another repository. +Tests use synthetic local fixtures. CI is configured for Python 3.10 and 3.14 on Linux, Windows and macOS; assess its result for the exact published commit separately from local verification. Edit `src/checker.py`, `src/adapters.py`, `vendor/common.py` or `rules/snapshot.json`, then rebuild with `python tools/build.py`. The generated checker has no runtime dependency on another repository. ## License @@ -79,3 +79,66 @@ Built by [CompleteTech LLC](https://complete.tech) ยท Innovation at Every Integr An interruption after a complete report is published preserves that report and exits 130. If an interrupt leaves file publication indeterminate, the checker exits 130 without retrying. Inspect the output before retrying; the diagnostic does not establish whether publication succeeded. + +## Explicit local metadata and source adapters + +```sh +python sharp_rsvg_rce_check.py --npm-lock examples/package-lock.example.json --evidence-root examples +python sharp_rsvg_rce_check.py --source examples/source.example.js --evidence-root examples --format html +python sharp_rsvg_rce_check.py --node-elf path/to/node --evidence-root path/to +python sharp_rsvg_rce_check.py --sbom path/to/bom.json --evidence-root path/to +``` + +The repeatable `--npm-lock`, `--sbom`, `--node-elf` and `--source` options require +`--evidence-root`. Selected files must resolve inside that directory; paths in +reports are relative. They may accompany existing inventory/version inputs, but +produce separate generated `adapter-*` asset records. Generated identifiers must +not collide with supplied inventory IDs. No directory search, package-manager +operation, application import, native execution or image decoding occurs. + +All adapter results remain `unknown` with `not_tested` exploitability. Metadata +cannot identify a deployed native-library selection or publisher patch +provenance. It never fills operator preconditions, changes a separate version +assessment or establishes effective mitigation. The existing schema 1.0 evidence +contract carries these observations as inventory/source evidence and locations; +JSON, CSV and HTML use the same validated records. + +- npm lock v1/v2/v3: extract Sharp package version observations, including nested + instances and explicit aliases. Linked/malformed/qualified identities stay + unknown. Legacy v2 dependency records are separate uncertain observations, + never used to clear a conflicting primary entry. Registry URLs and scripts + are not collected. Empty supported coverage does not establish absence. +- SBOM: support JSON CycloneDX 1.4/1.5/1.6 and SPDX 2.2/2.3 Sharp/librsvg package + metadata. Names and versions remain supplied metadata, not linkage evidence; + no external references are fetched and no package paths are opened. +- ELF: read the identification/header, at most 1,024 standard-size program + headers and one interpreter string (512 bytes maximum). Support ELF32/64 in + both byte orders; bound file size to 2 GiB and metadata reads to 58 KiB. Reject + truncated/out-of-file tables/segments, duplicate interpreters, extended header + counts and unsupported layouts. ET_DYN with an interpreter is a dynamic + executable candidate; ET_DYN alone can also be a shared library or static PIE. + ET_EXEC and interpreter basename hints are reported without asserting Node + identity, loaded libc, runtime PIE, patch state or safety. Exact loader paths + are not reported. Other hardening features are not analyzed. +- Source: explicitly select JS/TS files. Simple Sharp default imports/CommonJS + bindings identify factory and block/unblock call candidates with relative + lines. An SVG-loader marker in a bounded local window can belong to unrelated + code. No match, missing marker, unknown options, inactive blocks, shadowing, + ordering or dynamic syntax never establishes effective blocking or input + trust. Templates and regex/division ambiguity require manual review. Source + strings/snippets are not reported. + +Budgets: 100 adapter files, 1,000 combined result records, bounded 4 MiB JSON/text +reads and the existing JSON structure/depth limit; 10,000 package metadata +entries, 200,000 source tokens/file and 100 source candidates/file. Ordinary +regular-file checks require stable evidence copies, not a filesystem sandbox. +Output protection includes all selected evidence files and aliases, even with +--force. `--fail-on-unknown` includes these unknown adapter records. + +Format provenance reviewed 2026-10-25: [Linux ELF header/program-header layouts](https://github.com/torvalds/linux/blob/master/include/uapi/linux/elf.h), +[npm lock grammar](https://docs.npmjs.com/cli/v11/configuring-npm/package-lock-json/), +[CycloneDX 1.6 schema](https://github.com/CycloneDX/specification/blob/master/schema/bom-1.6.schema.json) and +[SPDX package fields](https://spdx.github.io/spdx-spec/v2.3.1/package-information/). +The Linux Foundation gABI pages were access-denied; no access restriction was +bypassed. Advisory thresholds, rule date and native affected-range uncertainty +are unchanged. Edit `src/adapters.py` and rebuild with `python tools/build.py`. diff --git a/SHA256SUMS b/SHA256SUMS index f47c907..b345ad0 100644 --- a/SHA256SUMS +++ b/SHA256SUMS @@ -1,2 +1,2 @@ -1bcaeb2b9e138be1caeb38ecf622368f96b19180c21bdc305818907f085841c6 sharp_rsvg_rce_check.py +8e1f8aa20f18eff0ab83c4d3a30b96923107215b44ea3ed243ce0c0b8c06e5ad sharp_rsvg_rce_check.py dbcee01397d62d0017fea9319fcb8d59a36b5bf0dfe16556f890cca498c848f6 rules/snapshot.json diff --git a/docs/IMPLEMENTATION.md b/docs/IMPLEMENTATION.md index 67603c7..0a1c37e 100644 --- a/docs/IMPLEMENTATION.md +++ b/docs/IMPLEMENTATION.md @@ -18,3 +18,7 @@ The original research foundation is preserved in Git history and `advisory.json` - [ ] Complete independent review and verify hosted CI for the exact final PR commit before merge. No real system was assessed during implementation. Local verification, hosted CI and independent review are separate evidence. A rule enabled in this implementation does not establish live exposure, exploitation or production readiness. + +## Local metadata adapters (2026-10-25) + +Implemented bounded npm/SBOM package observations, explicit ELF header/program metadata inspection and Sharp source input/block/unblock candidates. Results preserve the existing schema and remain separate unknown records; no runtime precondition, effective mitigation or native patch provenance is inferred. Synthetic ELF32/64/endian/layout/truncation, metadata/link/SBOM, source inactivity, output-protection/parity and standalone tests are included. GitHub Copilot review and exact-head CI are required before merge. diff --git a/docs/METHODOLOGY.md b/docs/METHODOLOGY.md index 04c1757..a4fac22 100644 --- a/docs/METHODOLOGY.md +++ b/docs/METHODOLOGY.md @@ -8,6 +8,8 @@ Custom and global linkage require a separate decision. A fixed Sharp package can The advisory describes possible RCE under runtime conditions on glibc Linux and identifies two workarounds: blocking the SVG loader and running a Node executable compiled with PIE. The checker records these dimensions separately. Effective SVG blocking is a decoder mitigation; PIE mitigates the documented RCE condition while other impact from the memory bug may remain. Neither is treated as a fixed library. No assumption about PIE is derived from a Node version, package source, platform or a vendor's usual build policy. -An operator must establish the input path and effective process configuration independently. Merely finding a block call in source would not show that it applies before all image decoding, and this tool performs no such source scan. It accepts controlled observations without executing application code. Missing libc or PIE remains unknown; absent runtime conditions do not prove that the library memory bug is absent. All local reachability and exploitability remain `not_tested`, including when every reported condition is present. +An operator must establish the input path and effective process configuration independently. Merely finding a block call in source would not show that it applies before all image decoding, and the optional source scanner reports only separate lexical candidates. It accepts controlled observations without executing application code. Missing libc or PIE remains unknown; absent runtime conditions do not prove that the library memory bug is absent. All local reachability and exploitability remain `not_tested`, including when every reported condition is present. Use build records, native linkage evidence and documented vendor patch provenance from the deployment being assessed. Keep conflicting evidence together; do not delete it or relabel a build to obtain a fixed result. Consult current upstream/vendor guidance, rebuild and redeploy as appropriate, and verify the effective deployed process separately. There is no public-website mode because ordinary response metadata cannot answer these questions. + +The 2026-10-25 adapters emit separate unknown records: neither an ELF layout hint nor a lexical block call is an established runtime precondition or mitigation. Metadata package versions do not attest library selection or provenance. See the reference for exact format coverage and bounds. diff --git a/docs/REFERENCE.md b/docs/REFERENCE.md index 3519dff..3fa437a 100644 --- a/docs/REFERENCE.md +++ b/docs/REFERENCE.md @@ -63,3 +63,66 @@ A reported fixed component does not fail the unknown gate solely for missing opt ## Reproducibility `rules/snapshot.json` is embedded by `tools/build.py`; reports include its canonical SHA-256 (sorted keys, compact JSON, UTF-8 and final newline). `SHA256SUMS` covers the generated single file and source snapshot. Checksums detect differences; they are not publisher signatures. `python tools/build.py --check` verifies both the generated source and release checksums. Runtime assessment never fetches a rule update. + +## Explicit local metadata and source adapters + +```sh +python sharp_rsvg_rce_check.py --npm-lock examples/package-lock.example.json --evidence-root examples +python sharp_rsvg_rce_check.py --source examples/source.example.js --evidence-root examples --format html +python sharp_rsvg_rce_check.py --node-elf path/to/node --evidence-root path/to +python sharp_rsvg_rce_check.py --sbom path/to/bom.json --evidence-root path/to +``` + +The repeatable `--npm-lock`, `--sbom`, `--node-elf` and `--source` options require +`--evidence-root`. Selected files must resolve inside that directory; paths in +reports are relative. They may accompany existing inventory/version inputs, but +produce separate generated `adapter-*` asset records. Generated identifiers must +not collide with supplied inventory IDs. No directory search, package-manager +operation, application import, native execution or image decoding occurs. + +All adapter results remain `unknown` with `not_tested` exploitability. Metadata +cannot identify a deployed native-library selection or publisher patch +provenance. It never fills operator preconditions, changes a separate version +assessment or establishes effective mitigation. The existing schema 1.0 evidence +contract carries these observations as inventory/source evidence and locations; +JSON, CSV and HTML use the same validated records. + +- npm lock v1/v2/v3: extract Sharp package version observations, including nested + instances and explicit aliases. Linked/malformed/qualified identities stay + unknown. Legacy v2 dependency records are separate uncertain observations, + never used to clear a conflicting primary entry. Registry URLs and scripts + are not collected. Empty supported coverage does not establish absence. +- SBOM: support JSON CycloneDX 1.4/1.5/1.6 and SPDX 2.2/2.3 Sharp/librsvg package + metadata. Names and versions remain supplied metadata, not linkage evidence; + no external references are fetched and no package paths are opened. +- ELF: read the identification/header, at most 1,024 standard-size program + headers and one interpreter string (512 bytes maximum). Support ELF32/64 in + both byte orders; bound file size to 2 GiB and metadata reads to 58 KiB. Reject + truncated/out-of-file tables/segments, duplicate interpreters, extended header + counts and unsupported layouts. ET_DYN with an interpreter is a dynamic + executable candidate; ET_DYN alone can also be a shared library or static PIE. + ET_EXEC and interpreter basename hints are reported without asserting Node + identity, loaded libc, runtime PIE, patch state or safety. Exact loader paths + are not reported. Other hardening features are not analyzed. +- Source: explicitly select JS/TS files. Simple Sharp default imports/CommonJS + bindings identify factory and block/unblock call candidates with relative + lines. An SVG-loader marker in a bounded local window can belong to unrelated + code. No match, missing marker, unknown options, inactive blocks, shadowing, + ordering or dynamic syntax never establishes effective blocking or input + trust. Templates and regex/division ambiguity require manual review. Source + strings/snippets are not reported. + +Budgets: 100 adapter files, 1,000 combined result records, bounded 4 MiB JSON/text +reads and the existing JSON structure/depth limit; 10,000 package metadata +entries, 200,000 source tokens/file and 100 source candidates/file. Ordinary +regular-file checks require stable evidence copies, not a filesystem sandbox. +Output protection includes all selected evidence files and aliases, even with +--force. `--fail-on-unknown` includes these unknown adapter records. + +Format provenance reviewed 2026-10-25: [Linux ELF header/program-header layouts](https://github.com/torvalds/linux/blob/master/include/uapi/linux/elf.h), +[npm lock grammar](https://docs.npmjs.com/cli/v11/configuring-npm/package-lock-json/), +[CycloneDX 1.6 schema](https://github.com/CycloneDX/specification/blob/master/schema/bom-1.6.schema.json) and +[SPDX package fields](https://spdx.github.io/spdx-spec/v2.3.1/package-information/). +The Linux Foundation gABI pages were access-denied; no access restriction was +bypassed. Advisory thresholds, rule date and native affected-range uncertainty +are unchanged. Edit `src/adapters.py` and rebuild with `python tools/build.py`. diff --git a/examples/package-lock.example.json b/examples/package-lock.example.json new file mode 100644 index 0000000..82489e4 --- /dev/null +++ b/examples/package-lock.example.json @@ -0,0 +1 @@ +{"lockfileVersion":3,"packages":{"node_modules/sharp":{"version":"0.35.4"}}} diff --git a/examples/source.example.js b/examples/source.example.js new file mode 100644 index 0000000..0c2e999 --- /dev/null +++ b/examples/source.example.js @@ -0,0 +1,4 @@ +// Synthetic text fixture, never executed. +const image = require('sharp'); +image.block({operation:['VipsForeignLoadSvg']}); +image(operatorInput); diff --git a/sharp_rsvg_rce_check.py b/sharp_rsvg_rce_check.py index 453f891..e99ca9d 100644 --- a/sharp_rsvg_rce_check.py +++ b/sharp_rsvg_rce_check.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 # SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-CompleteTech-Commercial # Copyright (c) 2026 CompleteTech LLC. See LICENSING.md. -# Generated by tools/build.py. Edit src/checker.py and vendor/common.py. +# Generated by tools/build.py. Edit src/checker.py, src/adapters.py and vendor/common.py. # Vendored common.py SHA-256: 714fb820175dc3d2dcb967928df4e1e97ad6fa0d478901ff6dba985f1368c0f7 from __future__ import annotations @@ -575,6 +575,313 @@ def save_report(path, text, force=False, protected_paths=(), state=None): RULE_SNAPSHOT = {'schema_version': '1.0', 'snapshot_id': 'sharp-rsvg-2026-10-24.1', 'created_at': '2026-10-24', 'rules': [{'id': 'CVE-2026-96889', 'revision': 1, 'title': 'Sharp librsvg memory vulnerability', 'component': 'sharp', 'advisories': ['CVE-2026-96889', 'GHSA-wq5f-xc86-pv6w'], 'enabled': True, 'verification_status': 'verified', 'verified_at': '2026-10-24', 'version_scheme': 'semver', 'affected': [{'branch': 'official Sharp bundles through 0.35.x', 'introduced': None, 'fixed': '0.35.5', 'last_affected': None, 'source_ids': ['sharp-maintainer']}], 'preconditions': [{'id': 'glibc-linux', 'description': 'The documented possible RCE conditions include glibc-based Linux; platform absence does not establish absence of the memory bug.', 'source_ids': ['sharp-maintainer']}, {'id': 'svg-decoding', 'description': 'SVG decoding is enabled in the deployed Sharp process.', 'source_ids': ['sharp-maintainer']}, {'id': 'node-without-pie', 'description': 'The deployed Node executable lacks PIE, the documented RCE mitigation.', 'source_ids': ['sharp-maintainer']}, {'id': 'untrusted-svg-input', 'description': 'Operator review indicates an untrusted SVG input path; this tool does not test data flow or reachability.', 'source_ids': ['sharp-maintainer']}], 'mitigations': [{'id': 'svg-block', 'description': 'Effective blocking of VipsForeignLoadSvg prevents Sharp SVG decoding; source text alone is insufficient.', 'source_ids': ['sharp-maintainer']}, {'id': 'node-pie', 'description': 'Node PIE mitigates the documented RCE condition; it does not establish library patch state or remove other memory-corruption impact.', 'source_ids': ['sharp-maintainer']}], 'sources': [{'id': 'sharp-maintainer', 'url': 'https://github.com/lovell/sharp/security/advisories/GHSA-wq5f-xc86-pv6w', 'publisher': 'Sharp maintainer', 'verified_at': '2026-10-24'}, {'id': 'github-advisory', 'url': 'https://github.com/advisories/GHSA-wq5f-xc86-pv6w', 'publisher': 'GitHub Advisory Database', 'verified_at': '2026-10-24'}], 'notes': ['Maintainer advisory: Sharp <0.35.5; patched >=0.35.5. The shipped snapshot restricts future comparison to the reviewed 0.35 release line and older 0.x versions.', 'Sharp 0.35.5 provides librsvg 2.63.2 in its official prebuilt binaries. Custom and global linkage require independent evidence.', 'The advisory names librsvg 2.63.2 remediation but publishes no separate librsvg affected-range lower bound. Older global librsvg remains unknown requiring remediation review; only stable 2.63.2+ in the 2.63 line is accepted as reported remediation.', "The GitHub database patched-version header says 0.35.5; its description agrees with the maintainer. The maintainer's >=0.35.5 statement governs the bundled comparison.", 'Every assessment is operator-reported evidence. Exploitability and reachability remain not_tested.']}]} +# SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-CompleteTech-Commercial +# Copyright (c) 2026 CompleteTech LLC. See LICENSING.md. +"""Bounded metadata adapters. These observations never attest runtime selection.""" +import struct + + +def adapter_path(path, root): + relative = Path(path).resolve().relative_to(Path(root).resolve()).as_posix() + validate_schema(relative, {"type": "string", "format": "relative-path", "maxLength": 512}) + return relative + + +def adapter_result(asset_id, component, evidence, *, version=None): + return make_result(asset_id, component, RULE_ID, "unknown", version=version, + version_assessment="unknown", build_source="unknown", evidence=evidence, + reasons=["File metadata and lexical source candidates do not establish deployed library selection, build provenance or runtime conditions."], + recommendation=RECOMMENDATION, sources=SOURCES) + + +def inspect_elf(path): + """Inspect at most 64 + 57,344 + 512 bytes, never map/load/execute an ELF.""" + before = Path(path).lstat() + if not stat.S_ISREG(before.st_mode): + raise ContractError("ELF must be a regular file, not a link or special file") + fd = os.open(path, os.O_RDONLY | getattr(os, "O_BINARY", 0) | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_NOFOLLOW", 0)) + with os.fdopen(fd, "rb") as stream: + info = os.fstat(stream.fileno()) + if (before.st_dev, before.st_ino) != (info.st_dev, info.st_ino): + raise ContractError("ELF identity changed while opening") + if not stat.S_ISREG(info.st_mode) or info.st_size > 2 * 1024**3: + raise ContractError("ELF must be a bounded regular file") + header = stream.read(64) + if len(header) < 16 or header[:4] != b"\x7fELF" or header[4] not in {1, 2} or header[5] not in {1, 2} or header[6] != 1: + raise ContractError("Unsupported ELF identification") + bits, endian = header[4], "<" if header[5] == 1 else ">" + fmt = endian + ("HHIIIIIHHHHHH" if bits == 1 else "HHIQQQIHHHHHH") + size = 16 + struct.calcsize(fmt) + if len(header) < size: + raise ContractError("Truncated ELF header") + fields = struct.unpack_from(fmt, header, 16) + file_type, _, version, _, offset, _, _, ehsize, entry_size, count, *_ = fields + expected = 32 if bits == 1 else 56 + if version != 1 or ehsize != size or count > 1024 or (count and entry_size != expected): + raise ContractError("Unsupported ELF header layout") + if count and (offset < size or offset + count * entry_size > info.st_size): + raise ContractError("ELF program header table is outside the file") + if count: + stream.seek(offset) + program_headers = stream.read(count * entry_size) + if len(program_headers) != count * entry_size: + raise ContractError("Truncated ELF program headers") + interpreter = None + for index in range(count): + ph = struct.unpack_from(endian + ("IIIIIIII" if bits == 1 else "IIQQQQQQ"), program_headers, index * entry_size) + kind, segment_offset, length = (ph[0], ph[1], ph[4]) if bits == 1 else (ph[0], ph[2], ph[5]) + if kind == 0: # PT_NULL fields other than p_type are undefined. + continue + if segment_offset + length > info.st_size: + raise ContractError("ELF segment is outside the file") + if kind == 3: + if interpreter is not None or length < 2 or length > 512: + raise ContractError("Invalid or duplicate ELF interpreter") + stream.seek(segment_offset) + raw = stream.read(length) + if len(raw) != length or not raw.endswith(b"\0") or b"\0" in raw[:-1]: + raise ContractError("Invalid ELF interpreter string") + try: + interpreter = raw[:-1].decode("ascii") + except UnicodeError: + raise ContractError("Unsupported ELF interpreter encoding") from None + # ET_DYN alone also describes a shared library or static PIE. Even an + # interpreter-bearing ET_DYN is only a binary-layout candidate here. + layout = "fixed_address_executable_candidate" if file_type == 2 else "dynamic_executable_candidate" if file_type == 3 and interpreter else "shared_or_static_pie_unknown" if file_type == 3 else "unknown" + basename = (interpreter or "").rsplit("/", 1)[-1] + libc = "musl_loader_candidate" if basename.startswith("ld-musl-") else "glibc_loader_candidate" if basename.startswith("ld-linux") else "unknown" + return {"class": 32 if bits == 1 else 64, "layout": layout, "libc": libc} + + +def elf_result(path, root, asset_id): + relative = adapter_path(path, root) + observed = inspect_elf(path) + detail = (f"ELF{observed['class']} metadata: layout={observed['layout']}; libc={observed['libc']}. " + "The file is not verified as the deployed Node executable; interpreter naming is a hint, not loaded-libc evidence. " + "PIE/libc/runtime mitigation remain unknown. No binary was executed or mapped.") + return adapter_result(asset_id, "ELF metadata (runtime identity unverified)", + [{"id": "elf-layout", "kind": "inventory", "state": "candidate", "detail": detail, "path": relative}]) + + +def _metadata_version_result(component, version, relative, asset_id, *, uncertain=False): + if version is not None and not isinstance(version, str): + raise ContractError("Metadata version must be text or missing") + exact = exact_version(version) if isinstance(version, str) else None + value = version if exact and not uncertain else None + detail = component + " metadata version: " + (value or "missing, qualified, linked or conflicting") + ". Library linkage and build provenance remain unknown; this is not a patch verdict." + return adapter_result(asset_id, component + " package metadata", [{"id": "metadata-version", "kind": "inventory", + "state": "present" if value else "unknown", "detail": detail, "path": relative}], version=value) + + +def metadata_results(path, root, mode, prefix): + relative = adapter_path(path, root) + data = load_json(path) + if not isinstance(data, dict): + raise ContractError("Metadata must be an object") + selected = [] + if mode == "npm": + lv = data.get("lockfileVersion") + if type(lv) is not int or lv not in {1, 2, 3}: + raise ContractError("Unsupported npm lock version") + if lv in {2, 3}: + packages = data.get("packages") + if not isinstance(packages, dict) or len(packages) > 10000: + raise ContractError("Invalid or excessive npm packages") + for location, item in packages.items(): + if not isinstance(item, dict) or not isinstance(location, str) or len(location) > 512: + raise ContractError("Invalid npm package metadata") + if "link" in item and type(item["link"]) is not bool: + raise ContractError("Invalid npm link flag") + canonical = location == "node_modules/sharp" or location.endswith("/node_modules/sharp") + if canonical or item.get("name") == "sharp": + selected.append(("Sharp", item.get("version"), bool(item.get("link")) or (canonical and item.get("name", "sharp") != "sharp"))) + if lv == 1 or "dependencies" in data: + pending = [(data.get("dependencies", {}), 0)] + count = 0 + while pending: + dependencies, depth = pending.pop() + if not isinstance(dependencies, dict) or depth > 30: + raise ContractError("Invalid dependency tree") + for name, item in dependencies.items(): + count += 1 + if count > 10000 or not isinstance(item, dict): + raise ContractError("Invalid or excessive dependencies") + if "link" in item and type(item["link"]) is not bool: + raise ContractError("Invalid npm link flag") + alias = isinstance(item.get("version"), str) and item["version"].startswith("npm:sharp@") + if name == "sharp" or item.get("name") == "sharp" or alias: + selected.append(("Sharp", item.get("version"), bool(item.get("link")) or lv != 1)) + if "dependencies" in item: + pending.append((item["dependencies"], depth + 1)) + elif data.get("bomFormat") == "CycloneDX" and isinstance(data.get("specVersion"), str) and data["specVersion"] in {"1.4", "1.5", "1.6"}: + pending = [data.get("components", [])] + metadata = data.get("metadata", {}) + if not isinstance(metadata, dict): + raise ContractError("Invalid SBOM metadata") + if "component" in metadata: + if not isinstance(metadata["component"], dict): + raise ContractError("Invalid SBOM subject component") + pending.append([metadata["component"]]) + count = 0 + while pending: + components = pending.pop() + if not isinstance(components, list): + raise ContractError("Invalid SBOM component list") + for item in components: + count += 1 + if count > 10000 or not isinstance(item, dict): + raise ContractError("Invalid or excessive SBOM components") + if "name" in item and not isinstance(item["name"], str): + raise ContractError("SBOM component name must be text") + if item.get("name") in {"sharp", "librsvg"}: + selected.append(("Sharp" if item["name"] == "sharp" else "librsvg", item.get("version"), False)) + if "components" in item: + pending.append(item["components"]) + elif isinstance(data.get("spdxVersion"), str) and data["spdxVersion"] in {"SPDX-2.2", "SPDX-2.3"}: + packages = data.get("packages", []) + if not isinstance(packages, list) or len(packages) > 10000: + raise ContractError("Invalid or excessive SPDX packages") + for item in packages: + if not isinstance(item, dict): + raise ContractError("Invalid SPDX package") + if "name" in item and not isinstance(item["name"], str): + raise ContractError("SPDX package name must be text") + if item.get("name") in {"sharp", "librsvg"}: + selected.append(("Sharp" if item["name"] == "sharp" else "librsvg", item.get("versionInfo"), False)) + else: + raise ContractError("Unsupported SBOM format/version") + if len(selected) > MAX_RECORDS: + raise ContractError("Too many selected metadata records") + if not selected: + return [adapter_result(prefix + "-coverage", "Package metadata coverage", [{"id": "coverage", "kind": "inventory", "state": "unknown", + "path": relative, "detail": "No supported Sharp/librsvg metadata observation found; absence and deployed selection are not established."}])] + return [_metadata_version_result(component, version, relative, prefix + "-" + str(index + 1), uncertain=uncertain) + for index, (component, version, uncertain) in enumerate(selected)] + + +# Lexer bundled from vm2-nesting-check 1cd5347, under the same licensing. +def _js_tokens(text): + """Bounded lexical hints, not a JavaScript parser. Never retain source strings.""" + text = text.replace("\r\n", "\n").replace("\r", "\n").replace("\u2028", "\n").replace("\u2029", "\n") + tokens = [] + index, line = 0, 1 + while index < len(text): + start = index + char = text[index] + if char.isspace(): + line += char == "\n" + index += 1 + continue + if text.startswith("//", index): + end = text.find("\n", index) + index = len(text) if end < 0 else end + continue + if text.startswith("/*", index): + end = text.find("*/", index + 2) + if end < 0: + raise ValueError("Unterminated JavaScript comment") + line += text.count("\n", index, end + 2) + index = end + 2 + continue + token_line = line + if char in "\"'`": + index += 1 + while index < len(text): + if text[index] == "\\": + index += 2 + elif text[index] == char: + index += 1 + break + else: + index += 1 + else: + raise ValueError("Unterminated JavaScript string or template") + raw = text[start + 1:index - 1] + value = "@template" if char == "`" else "@" + raw if raw in {"sharp", "VipsForeignLoadSvg", "operation"} else "@string" + line += text.count("\n", start, index) + elif char == "/" and (not tokens or tokens[-1][0] in {"=", "(", "[", "{", ":", ",", ";", "return", "=>"}): + # Regex bodies are opaque. Templates (including interpolations) are + # also opaque; the report always states incomplete lexical coverage. + index += 1 + in_class = False + while index < len(text): + c = text[index] + if c == "\\": + index += 2 + continue + if c == "[": + in_class = True + elif c == "]": + in_class = False + elif c == "/" and not in_class: + index += 1 + break + elif c == "\n": + raise ValueError("Unterminated JavaScript regex candidate") + index += 1 + else: + raise ValueError("Unterminated JavaScript regex candidate") + value = "@regex" + elif char.isascii() and (char.isalpha() or char in "_$"): + index += 1 + while index < len(text) and text[index].isascii() and (text[index].isalnum() or text[index] in "_$"): + index += 1 + value = text[start:index] + elif text.startswith("=>", index): + value, index = "=>", index + 2 + elif text.startswith("...", index): + value, index = "...", index + 3 + else: + value, index = char, index + 1 + tokens.append((value, token_line)) + if len(tokens) > 200000: + raise ValueError("Source exceeds the 200,000 token limit") + return tokens + + +def source_results(path, root, prefix): + relative = adapter_path(path, root) + text = _read_regular_file(path, MAX_JSON_BYTES).decode("utf-8-sig") + tokens = _js_tokens(text) + values = [token[0] for token in tokens] + bindings = set() + ident = r"[A-Za-z_$][A-Za-z0-9_$]*" + for index, value in enumerate(values): + if value not in {"import", "const", "let", "var"}: + continue + statement = " ".join(values[index:index + 20]) + match = re.match(r"import (" + ident + r") from @sharp(?: |$)", statement) + if not match: + match = re.match(r"(?:const|let|var) (" + ident + r") = require \( @sharp \)", statement) + if match: + bindings.add(match[1]) + evidence = [] + for index, value in enumerate(values[:-1]): + if value not in bindings: + continue + operation, detail = None, "" + if values[index + 1] == "(": + operation = "decode-input" + detail = "Import-associated Sharp factory call candidate. Input format, attacker control and deployed execution remain unknown." + elif (index + 3 < len(values) and values[index + 1] == "." and values[index + 2] in {"block", "unblock"} + and values[index + 3] == "("): + operation = values[index + 2] + # A small local window is a search hint, never effective mitigation. + marker = "present_in_window" if "@VipsForeignLoadSvg" in values[index + 4:index + 68] else "not_observed_in_window" + detail = f"Sharp {operation} call candidate; SVG loader marker {marker}. The bounded window may include unrelated code. Ordering, branches, dynamic configuration and deployment are unresolved; no effective mitigation is inferred." + if operation: + evidence.append({"id": "source-" + str(len(evidence) + 1), "kind": "source", "state": "candidate", + "path": relative, "line": tokens[index][1], "detail": detail + " Aliases, shadowing, reassignment, templates, regex/division and unsupported syntax require manual review."}) + if len(evidence) > 100: + raise ContractError("Too many source candidates in one file") + if not evidence: + evidence.append({"id": "coverage", "kind": "source", "state": "unknown", "path": relative, + "detail": "No supported import-associated Sharp call candidate found. Coverage is limited lexical; absence, input trust and runtime mitigation are not established."}) + return [adapter_result(prefix, "Sharp source candidates", evidence)] + + + + # SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-CompleteTech-Commercial # Copyright (c) 2026 CompleteTech LLC. See LICENSING.md. """Offline Sharp/librsvg evidence assessment; never imports Sharp or decodes images.""" @@ -583,7 +890,7 @@ def save_report(path, text, force=False, protected_paths=(), state=None): import sys TOOL_NAME = "sharp-rsvg-rce-check" -TOOL_VERSION = "0.1.0" +TOOL_VERSION = "0.2.0" RULE_ID = "CVE-2026-96889" RULE_DATE = "2026-10-24" SNAPSHOT_ID = "sharp-rsvg-2026-10-24.1" @@ -613,7 +920,7 @@ def save_report(path, text, force=False, protected_paths=(), state=None): INPUT_SCHEMA = _object({"schema_version": {"const": "1.0"}, "records": _array(RECORD_SCHEMA, MAX_RECORDS, 1)}) LIMITATIONS = [ - "Offline operator-supplied evidence only; library selection, deployed versions, provenance and effective mitigations are not independently attested.", + "Offline supplied evidence and explicitly selected metadata only; library selection, deployed versions, provenance and effective mitigations are not independently attested.", "No network requests, application execution, image decoding, exploitation, reachability test or compromise detection is performed.", "The Sharp comparison covers exact stable 0.0-0.35 versions. Global librsvg has a documented remediation build, not a published independent affected-version range; only stable 2.63.2+ within 2.63 is accepted as reported remediation.", "PIE is an RCE mitigation, not a library patch or a guarantee against other memory-corruption impact. Unknown libc or PIE remains unknown.", @@ -716,7 +1023,7 @@ def assess_record(raw): details = { "glibc-linux": "Reported platform: " + platform + "; reported libc: " + libc + ". Other platforms do not establish that the underlying memory bug is absent.", "svg-decoding": "Reported effective SVG decoder state: " + record["svg_decoder"] + ". A blocked claim must cover VipsForeignLoadSvg in the deployed process.", - "node-without-pie": "Reported Node executable PIE state: " + record["node_pie"] + ". No binary inspection is performed.", + "node-without-pie": "Reported Node executable PIE state: " + record["node_pie"] + ". This operator claim is not inferred from optional binary metadata hints.", "untrusted-svg-input": "Operator-reviewed untrusted SVG input path: " + record["untrusted_svg"] + ". No data-flow or reachability test is performed.", } preconditions = [] @@ -763,6 +1070,11 @@ def publish_results(args, results, protected, *, complete, state=None): def build_parser(): parser = argparse.ArgumentParser(description="Offline CVE-2026-96889 Sharp/librsvg evidence assessment. No network, application execution or image decoding.") parser.add_argument("--inventory", type=Path, help="Bounded schema-v1 JSON inventory; cannot be combined with per-asset options.") + parser.add_argument("--npm-lock", action="append", default=[], type=Path, help="Explicit npm lock v1/v2/v3 metadata; never invokes npm") + parser.add_argument("--sbom", action="append", default=[], type=Path, help="Explicit CycloneDX 1.4-1.6 or SPDX 2.2/2.3 JSON metadata") + parser.add_argument("--node-elf", action="append", default=[], type=Path, help="Explicit ELF file for bounded layout/interpreter hints; never executed or attested as Node") + parser.add_argument("--source", action="append", default=[], type=Path, help="Explicit JS/TS file for import-associated Sharp input/block candidates") + parser.add_argument("--evidence-root", type=Path, help="Required for adapter files; evidence locations are relative to this directory") parser.add_argument("--sharp-version", action="append", dest="sharp_versions", help="Reported stable Sharp version; repeat to preserve conflicts.") parser.add_argument("--librsvg-version", action="append", dest="librsvg_versions", help="Independently reported native librsvg version; repeat to preserve conflicts.") parser.add_argument("--asset-id", help="Opaque identifier, at most 64 ASCII letters/digits/dot/underscore/hyphen; default asset-0001.") @@ -791,23 +1103,49 @@ def main(argv=None): selected = {key: getattr(args, key) for key in RECORD_SCHEMA["properties"] if getattr(args, key, None) is not None} if args.inventory and selected: parser.error("--inventory cannot be combined with per-asset options") - if not args.inventory and not (args.sharp_versions or args.librsvg_versions): - parser.error("provide --inventory, --sharp-version or --librsvg-version") + adapter_files = [*args.npm_lock, *args.sbom, *args.node_elf, *args.source] + if not args.inventory and not (args.sharp_versions or args.librsvg_versions or adapter_files): + parser.error("provide --inventory, a reported version or explicit adapter files") results, protected = [], [Path(__file__)] publication = {"stdout_started": False, "published": False} if args.inventory: protected.append(args.inventory) + protected.extend(adapter_files) if args.logo: protected.append(args.logo) try: if args.logo and args.format != "html": raise ContractError("logo requires HTML output") + if len(adapter_files) > 100 or (adapter_files and (args.evidence_root is None or not args.evidence_root.is_dir())): + raise ContractError("Adapter inputs require an evidence root and at most 100 files") + for path in adapter_files: + adapter_path(path, args.evidence_root) + for path in args.source: + if path.suffix.lower() not in {".js", ".cjs", ".mjs", ".ts", ".cts", ".mts", ".jsx", ".tsx"}: + raise ContractError("Source must be an explicit JS/TS file") if args.inventory: records = read_inventory(args.inventory) - else: + elif selected: records = [normalize_record({"asset_id": "asset-0001", **selected})] + else: + records = [] for record in records: results.append(assess_record(record)) + asset_ids = {result["asset_id"] for result in results} + for mode, files in [("npm", args.npm_lock), ("sbom", args.sbom), ("elf", args.node_elf), ("source", args.source)]: + for index, path in enumerate(files): + prefix = "adapter-" + mode + "-" + str(index + 1) + if mode == "elf": + added = [elf_result(path, args.evidence_root, prefix)] + elif mode == "source": + added = source_results(path, args.evidence_root, prefix) + else: + added = metadata_results(path, args.evidence_root, mode, prefix) + for result in added: + if result["asset_id"] in asset_ids or len(results) >= MAX_RECORDS: + raise ContractError("Duplicate or excessive combined result records") + asset_ids.add(result["asset_id"]) + results.append(result) publish_results(args, results, protected, complete=True, state=publication) if args.fail_on_finding and any(result["version_assessment"] == "affected" for result in results): return 1 diff --git a/src/adapters.py b/src/adapters.py new file mode 100644 index 0000000..0e93c2a --- /dev/null +++ b/src/adapters.py @@ -0,0 +1,305 @@ +# SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-CompleteTech-Commercial +# Copyright (c) 2026 CompleteTech LLC. See LICENSING.md. +"""Bounded metadata adapters. These observations never attest runtime selection.""" +import struct + + +def adapter_path(path, root): + relative = Path(path).resolve().relative_to(Path(root).resolve()).as_posix() + validate_schema(relative, {"type": "string", "format": "relative-path", "maxLength": 512}) + return relative + + +def adapter_result(asset_id, component, evidence, *, version=None): + return make_result(asset_id, component, RULE_ID, "unknown", version=version, + version_assessment="unknown", build_source="unknown", evidence=evidence, + reasons=["File metadata and lexical source candidates do not establish deployed library selection, build provenance or runtime conditions."], + recommendation=RECOMMENDATION, sources=SOURCES) + + +def inspect_elf(path): + """Inspect at most 64 + 57,344 + 512 bytes, never map/load/execute an ELF.""" + before = Path(path).lstat() + if not stat.S_ISREG(before.st_mode): + raise ContractError("ELF must be a regular file, not a link or special file") + fd = os.open(path, os.O_RDONLY | getattr(os, "O_BINARY", 0) | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_NOFOLLOW", 0)) + with os.fdopen(fd, "rb") as stream: + info = os.fstat(stream.fileno()) + if (before.st_dev, before.st_ino) != (info.st_dev, info.st_ino): + raise ContractError("ELF identity changed while opening") + if not stat.S_ISREG(info.st_mode) or info.st_size > 2 * 1024**3: + raise ContractError("ELF must be a bounded regular file") + header = stream.read(64) + if len(header) < 16 or header[:4] != b"\x7fELF" or header[4] not in {1, 2} or header[5] not in {1, 2} or header[6] != 1: + raise ContractError("Unsupported ELF identification") + bits, endian = header[4], "<" if header[5] == 1 else ">" + fmt = endian + ("HHIIIIIHHHHHH" if bits == 1 else "HHIQQQIHHHHHH") + size = 16 + struct.calcsize(fmt) + if len(header) < size: + raise ContractError("Truncated ELF header") + fields = struct.unpack_from(fmt, header, 16) + file_type, _, version, _, offset, _, _, ehsize, entry_size, count, *_ = fields + expected = 32 if bits == 1 else 56 + if version != 1 or ehsize != size or count > 1024 or (count and entry_size != expected): + raise ContractError("Unsupported ELF header layout") + if count and (offset < size or offset + count * entry_size > info.st_size): + raise ContractError("ELF program header table is outside the file") + if count: + stream.seek(offset) + program_headers = stream.read(count * entry_size) + if len(program_headers) != count * entry_size: + raise ContractError("Truncated ELF program headers") + interpreter = None + for index in range(count): + ph = struct.unpack_from(endian + ("IIIIIIII" if bits == 1 else "IIQQQQQQ"), program_headers, index * entry_size) + kind, segment_offset, length = (ph[0], ph[1], ph[4]) if bits == 1 else (ph[0], ph[2], ph[5]) + if kind == 0: # PT_NULL fields other than p_type are undefined. + continue + if segment_offset + length > info.st_size: + raise ContractError("ELF segment is outside the file") + if kind == 3: + if interpreter is not None or length < 2 or length > 512: + raise ContractError("Invalid or duplicate ELF interpreter") + stream.seek(segment_offset) + raw = stream.read(length) + if len(raw) != length or not raw.endswith(b"\0") or b"\0" in raw[:-1]: + raise ContractError("Invalid ELF interpreter string") + try: + interpreter = raw[:-1].decode("ascii") + except UnicodeError: + raise ContractError("Unsupported ELF interpreter encoding") from None + # ET_DYN alone also describes a shared library or static PIE. Even an + # interpreter-bearing ET_DYN is only a binary-layout candidate here. + layout = "fixed_address_executable_candidate" if file_type == 2 else "dynamic_executable_candidate" if file_type == 3 and interpreter else "shared_or_static_pie_unknown" if file_type == 3 else "unknown" + basename = (interpreter or "").rsplit("/", 1)[-1] + libc = "musl_loader_candidate" if basename.startswith("ld-musl-") else "glibc_loader_candidate" if basename.startswith("ld-linux") else "unknown" + return {"class": 32 if bits == 1 else 64, "layout": layout, "libc": libc} + + +def elf_result(path, root, asset_id): + relative = adapter_path(path, root) + observed = inspect_elf(path) + detail = (f"ELF{observed['class']} metadata: layout={observed['layout']}; libc={observed['libc']}. " + "The file is not verified as the deployed Node executable; interpreter naming is a hint, not loaded-libc evidence. " + "PIE/libc/runtime mitigation remain unknown. No binary was executed or mapped.") + return adapter_result(asset_id, "ELF metadata (runtime identity unverified)", + [{"id": "elf-layout", "kind": "inventory", "state": "candidate", "detail": detail, "path": relative}]) + + +def _metadata_version_result(component, version, relative, asset_id, *, uncertain=False): + if version is not None and not isinstance(version, str): + raise ContractError("Metadata version must be text or missing") + exact = exact_version(version) if isinstance(version, str) else None + value = version if exact and not uncertain else None + detail = component + " metadata version: " + (value or "missing, qualified, linked or conflicting") + ". Library linkage and build provenance remain unknown; this is not a patch verdict." + return adapter_result(asset_id, component + " package metadata", [{"id": "metadata-version", "kind": "inventory", + "state": "present" if value else "unknown", "detail": detail, "path": relative}], version=value) + + +def metadata_results(path, root, mode, prefix): + relative = adapter_path(path, root) + data = load_json(path) + if not isinstance(data, dict): + raise ContractError("Metadata must be an object") + selected = [] + if mode == "npm": + lv = data.get("lockfileVersion") + if type(lv) is not int or lv not in {1, 2, 3}: + raise ContractError("Unsupported npm lock version") + if lv in {2, 3}: + packages = data.get("packages") + if not isinstance(packages, dict) or len(packages) > 10000: + raise ContractError("Invalid or excessive npm packages") + for location, item in packages.items(): + if not isinstance(item, dict) or not isinstance(location, str) or len(location) > 512: + raise ContractError("Invalid npm package metadata") + if "link" in item and type(item["link"]) is not bool: + raise ContractError("Invalid npm link flag") + canonical = location == "node_modules/sharp" or location.endswith("/node_modules/sharp") + if canonical or item.get("name") == "sharp": + selected.append(("Sharp", item.get("version"), bool(item.get("link")) or (canonical and item.get("name", "sharp") != "sharp"))) + if lv == 1 or "dependencies" in data: + pending = [(data.get("dependencies", {}), 0)] + count = 0 + while pending: + dependencies, depth = pending.pop() + if not isinstance(dependencies, dict) or depth > 30: + raise ContractError("Invalid dependency tree") + for name, item in dependencies.items(): + count += 1 + if count > 10000 or not isinstance(item, dict): + raise ContractError("Invalid or excessive dependencies") + if "link" in item and type(item["link"]) is not bool: + raise ContractError("Invalid npm link flag") + alias = isinstance(item.get("version"), str) and item["version"].startswith("npm:sharp@") + if name == "sharp" or item.get("name") == "sharp" or alias: + selected.append(("Sharp", item.get("version"), bool(item.get("link")) or lv != 1)) + if "dependencies" in item: + pending.append((item["dependencies"], depth + 1)) + elif data.get("bomFormat") == "CycloneDX" and isinstance(data.get("specVersion"), str) and data["specVersion"] in {"1.4", "1.5", "1.6"}: + pending = [data.get("components", [])] + metadata = data.get("metadata", {}) + if not isinstance(metadata, dict): + raise ContractError("Invalid SBOM metadata") + if "component" in metadata: + if not isinstance(metadata["component"], dict): + raise ContractError("Invalid SBOM subject component") + pending.append([metadata["component"]]) + count = 0 + while pending: + components = pending.pop() + if not isinstance(components, list): + raise ContractError("Invalid SBOM component list") + for item in components: + count += 1 + if count > 10000 or not isinstance(item, dict): + raise ContractError("Invalid or excessive SBOM components") + if "name" in item and not isinstance(item["name"], str): + raise ContractError("SBOM component name must be text") + if item.get("name") in {"sharp", "librsvg"}: + selected.append(("Sharp" if item["name"] == "sharp" else "librsvg", item.get("version"), False)) + if "components" in item: + pending.append(item["components"]) + elif isinstance(data.get("spdxVersion"), str) and data["spdxVersion"] in {"SPDX-2.2", "SPDX-2.3"}: + packages = data.get("packages", []) + if not isinstance(packages, list) or len(packages) > 10000: + raise ContractError("Invalid or excessive SPDX packages") + for item in packages: + if not isinstance(item, dict): + raise ContractError("Invalid SPDX package") + if "name" in item and not isinstance(item["name"], str): + raise ContractError("SPDX package name must be text") + if item.get("name") in {"sharp", "librsvg"}: + selected.append(("Sharp" if item["name"] == "sharp" else "librsvg", item.get("versionInfo"), False)) + else: + raise ContractError("Unsupported SBOM format/version") + if len(selected) > MAX_RECORDS: + raise ContractError("Too many selected metadata records") + if not selected: + return [adapter_result(prefix + "-coverage", "Package metadata coverage", [{"id": "coverage", "kind": "inventory", "state": "unknown", + "path": relative, "detail": "No supported Sharp/librsvg metadata observation found; absence and deployed selection are not established."}])] + return [_metadata_version_result(component, version, relative, prefix + "-" + str(index + 1), uncertain=uncertain) + for index, (component, version, uncertain) in enumerate(selected)] + + +# Lexer bundled from vm2-nesting-check 1cd5347, under the same licensing. +def _js_tokens(text): + """Bounded lexical hints, not a JavaScript parser. Never retain source strings.""" + text = text.replace("\r\n", "\n").replace("\r", "\n").replace("\u2028", "\n").replace("\u2029", "\n") + tokens = [] + index, line = 0, 1 + while index < len(text): + start = index + char = text[index] + if char.isspace(): + line += char == "\n" + index += 1 + continue + if text.startswith("//", index): + end = text.find("\n", index) + index = len(text) if end < 0 else end + continue + if text.startswith("/*", index): + end = text.find("*/", index + 2) + if end < 0: + raise ValueError("Unterminated JavaScript comment") + line += text.count("\n", index, end + 2) + index = end + 2 + continue + token_line = line + if char in "\"'`": + index += 1 + while index < len(text): + if text[index] == "\\": + index += 2 + elif text[index] == char: + index += 1 + break + else: + index += 1 + else: + raise ValueError("Unterminated JavaScript string or template") + raw = text[start + 1:index - 1] + value = "@template" if char == "`" else "@" + raw if raw in {"sharp", "VipsForeignLoadSvg", "operation"} else "@string" + line += text.count("\n", start, index) + elif char == "/" and (not tokens or tokens[-1][0] in {"=", "(", "[", "{", ":", ",", ";", "return", "=>"}): + # Regex bodies are opaque. Templates (including interpolations) are + # also opaque; the report always states incomplete lexical coverage. + index += 1 + in_class = False + while index < len(text): + c = text[index] + if c == "\\": + index += 2 + continue + if c == "[": + in_class = True + elif c == "]": + in_class = False + elif c == "/" and not in_class: + index += 1 + break + elif c == "\n": + raise ValueError("Unterminated JavaScript regex candidate") + index += 1 + else: + raise ValueError("Unterminated JavaScript regex candidate") + value = "@regex" + elif char.isascii() and (char.isalpha() or char in "_$"): + index += 1 + while index < len(text) and text[index].isascii() and (text[index].isalnum() or text[index] in "_$"): + index += 1 + value = text[start:index] + elif text.startswith("=>", index): + value, index = "=>", index + 2 + elif text.startswith("...", index): + value, index = "...", index + 3 + else: + value, index = char, index + 1 + tokens.append((value, token_line)) + if len(tokens) > 200000: + raise ValueError("Source exceeds the 200,000 token limit") + return tokens + + +def source_results(path, root, prefix): + relative = adapter_path(path, root) + text = _read_regular_file(path, MAX_JSON_BYTES).decode("utf-8-sig") + tokens = _js_tokens(text) + values = [token[0] for token in tokens] + bindings = set() + ident = r"[A-Za-z_$][A-Za-z0-9_$]*" + for index, value in enumerate(values): + if value not in {"import", "const", "let", "var"}: + continue + statement = " ".join(values[index:index + 20]) + match = re.match(r"import (" + ident + r") from @sharp(?: |$)", statement) + if not match: + match = re.match(r"(?:const|let|var) (" + ident + r") = require \( @sharp \)", statement) + if match: + bindings.add(match[1]) + evidence = [] + for index, value in enumerate(values[:-1]): + if value not in bindings: + continue + operation, detail = None, "" + if values[index + 1] == "(": + operation = "decode-input" + detail = "Import-associated Sharp factory call candidate. Input format, attacker control and deployed execution remain unknown." + elif (index + 3 < len(values) and values[index + 1] == "." and values[index + 2] in {"block", "unblock"} + and values[index + 3] == "("): + operation = values[index + 2] + # A small local window is a search hint, never effective mitigation. + marker = "present_in_window" if "@VipsForeignLoadSvg" in values[index + 4:index + 68] else "not_observed_in_window" + detail = f"Sharp {operation} call candidate; SVG loader marker {marker}. The bounded window may include unrelated code. Ordering, branches, dynamic configuration and deployment are unresolved; no effective mitigation is inferred." + if operation: + evidence.append({"id": "source-" + str(len(evidence) + 1), "kind": "source", "state": "candidate", + "path": relative, "line": tokens[index][1], "detail": detail + " Aliases, shadowing, reassignment, templates, regex/division and unsupported syntax require manual review."}) + if len(evidence) > 100: + raise ContractError("Too many source candidates in one file") + if not evidence: + evidence.append({"id": "coverage", "kind": "source", "state": "unknown", "path": relative, + "detail": "No supported import-associated Sharp call candidate found. Coverage is limited lexical; absence, input trust and runtime mitigation are not established."}) + return [adapter_result(prefix, "Sharp source candidates", evidence)] + + diff --git a/src/checker.py b/src/checker.py index 04b9cf1..34f4116 100644 --- a/src/checker.py +++ b/src/checker.py @@ -6,7 +6,7 @@ import sys TOOL_NAME = "sharp-rsvg-rce-check" -TOOL_VERSION = "0.1.0" +TOOL_VERSION = "0.2.0" RULE_ID = "CVE-2026-96889" RULE_DATE = "2026-10-24" SNAPSHOT_ID = "sharp-rsvg-2026-10-24.1" @@ -36,7 +36,7 @@ INPUT_SCHEMA = _object({"schema_version": {"const": "1.0"}, "records": _array(RECORD_SCHEMA, MAX_RECORDS, 1)}) LIMITATIONS = [ - "Offline operator-supplied evidence only; library selection, deployed versions, provenance and effective mitigations are not independently attested.", + "Offline supplied evidence and explicitly selected metadata only; library selection, deployed versions, provenance and effective mitigations are not independently attested.", "No network requests, application execution, image decoding, exploitation, reachability test or compromise detection is performed.", "The Sharp comparison covers exact stable 0.0-0.35 versions. Global librsvg has a documented remediation build, not a published independent affected-version range; only stable 2.63.2+ within 2.63 is accepted as reported remediation.", "PIE is an RCE mitigation, not a library patch or a guarantee against other memory-corruption impact. Unknown libc or PIE remains unknown.", @@ -139,7 +139,7 @@ def assess_record(raw): details = { "glibc-linux": "Reported platform: " + platform + "; reported libc: " + libc + ". Other platforms do not establish that the underlying memory bug is absent.", "svg-decoding": "Reported effective SVG decoder state: " + record["svg_decoder"] + ". A blocked claim must cover VipsForeignLoadSvg in the deployed process.", - "node-without-pie": "Reported Node executable PIE state: " + record["node_pie"] + ". No binary inspection is performed.", + "node-without-pie": "Reported Node executable PIE state: " + record["node_pie"] + ". This operator claim is not inferred from optional binary metadata hints.", "untrusted-svg-input": "Operator-reviewed untrusted SVG input path: " + record["untrusted_svg"] + ". No data-flow or reachability test is performed.", } preconditions = [] @@ -186,6 +186,11 @@ def publish_results(args, results, protected, *, complete, state=None): def build_parser(): parser = argparse.ArgumentParser(description="Offline CVE-2026-96889 Sharp/librsvg evidence assessment. No network, application execution or image decoding.") parser.add_argument("--inventory", type=Path, help="Bounded schema-v1 JSON inventory; cannot be combined with per-asset options.") + parser.add_argument("--npm-lock", action="append", default=[], type=Path, help="Explicit npm lock v1/v2/v3 metadata; never invokes npm") + parser.add_argument("--sbom", action="append", default=[], type=Path, help="Explicit CycloneDX 1.4-1.6 or SPDX 2.2/2.3 JSON metadata") + parser.add_argument("--node-elf", action="append", default=[], type=Path, help="Explicit ELF file for bounded layout/interpreter hints; never executed or attested as Node") + parser.add_argument("--source", action="append", default=[], type=Path, help="Explicit JS/TS file for import-associated Sharp input/block candidates") + parser.add_argument("--evidence-root", type=Path, help="Required for adapter files; evidence locations are relative to this directory") parser.add_argument("--sharp-version", action="append", dest="sharp_versions", help="Reported stable Sharp version; repeat to preserve conflicts.") parser.add_argument("--librsvg-version", action="append", dest="librsvg_versions", help="Independently reported native librsvg version; repeat to preserve conflicts.") parser.add_argument("--asset-id", help="Opaque identifier, at most 64 ASCII letters/digits/dot/underscore/hyphen; default asset-0001.") @@ -214,23 +219,49 @@ def main(argv=None): selected = {key: getattr(args, key) for key in RECORD_SCHEMA["properties"] if getattr(args, key, None) is not None} if args.inventory and selected: parser.error("--inventory cannot be combined with per-asset options") - if not args.inventory and not (args.sharp_versions or args.librsvg_versions): - parser.error("provide --inventory, --sharp-version or --librsvg-version") + adapter_files = [*args.npm_lock, *args.sbom, *args.node_elf, *args.source] + if not args.inventory and not (args.sharp_versions or args.librsvg_versions or adapter_files): + parser.error("provide --inventory, a reported version or explicit adapter files") results, protected = [], [Path(__file__)] publication = {"stdout_started": False, "published": False} if args.inventory: protected.append(args.inventory) + protected.extend(adapter_files) if args.logo: protected.append(args.logo) try: if args.logo and args.format != "html": raise ContractError("logo requires HTML output") + if len(adapter_files) > 100 or (adapter_files and (args.evidence_root is None or not args.evidence_root.is_dir())): + raise ContractError("Adapter inputs require an evidence root and at most 100 files") + for path in adapter_files: + adapter_path(path, args.evidence_root) + for path in args.source: + if path.suffix.lower() not in {".js", ".cjs", ".mjs", ".ts", ".cts", ".mts", ".jsx", ".tsx"}: + raise ContractError("Source must be an explicit JS/TS file") if args.inventory: records = read_inventory(args.inventory) - else: + elif selected: records = [normalize_record({"asset_id": "asset-0001", **selected})] + else: + records = [] for record in records: results.append(assess_record(record)) + asset_ids = {result["asset_id"] for result in results} + for mode, files in [("npm", args.npm_lock), ("sbom", args.sbom), ("elf", args.node_elf), ("source", args.source)]: + for index, path in enumerate(files): + prefix = "adapter-" + mode + "-" + str(index + 1) + if mode == "elf": + added = [elf_result(path, args.evidence_root, prefix)] + elif mode == "source": + added = source_results(path, args.evidence_root, prefix) + else: + added = metadata_results(path, args.evidence_root, mode, prefix) + for result in added: + if result["asset_id"] in asset_ids or len(results) >= MAX_RECORDS: + raise ContractError("Duplicate or excessive combined result records") + asset_ids.add(result["asset_id"]) + results.append(result) publish_results(args, results, protected, complete=True, state=publication) if args.fail_on_finding and any(result["version_assessment"] == "affected" for result in results): return 1 diff --git a/test_adapters.py b/test_adapters.py new file mode 100644 index 0000000..e915fe1 --- /dev/null +++ b/test_adapters.py @@ -0,0 +1,233 @@ +"""Synthetic ELF/package/source evidence. No native code or SVG is executed.""" +import contextlib +import io +import json +import os +from pathlib import Path +import struct +import subprocess +import sys +import tempfile +import unittest +from unittest import mock + +import sharp_rsvg_rce_check as c + + +def elf_fixture(bits=64, endian="<", kind=3, interpreter=b"/lib64/ld-linux-x86-64.so.2\0"): + ident = b"\x7fELF" + bytes([1 if bits == 32 else 2, 1 if endian == "<" else 2, 1]) + b"\0" * 9 + size, phsize = (52, 32) if bits == 32 else (64, 56) + count = int(interpreter is not None) + fmt = "HHIIIIIHHHHHH" if bits == 32 else "HHIQQQIHHHHHH" + header = struct.pack(endian + fmt, kind, 3 if bits == 32 else 62, 1, 0, size, 0, 0, size, phsize, count, 0, 0, 0) + program = b"" + if interpreter is not None: + offset = size + phsize + fields = (3, offset, 0, 0, len(interpreter), len(interpreter), 4, 1) if bits == 32 else (3, 4, offset, 0, 0, len(interpreter), len(interpreter), 1) + program = struct.pack(endian + ("IIIIIIII" if bits == 32 else "IIQQQQQQ"), *fields) + interpreter + return ident + header + program + + +class AdapterTests(unittest.TestCase): + def cli(self, *args): + with contextlib.redirect_stdout(io.StringIO()) as out, contextlib.redirect_stderr(io.StringIO()) as err: + code = c.main(list(args)) + return code, out.getvalue(), err.getvalue() + + def test_arrow_return_regex_body_is_opaque(self): + tokens = c._js_tokens("const pattern = () => /const image = require('sharp'); image(input)/;") + self.assertIn("@regex", [value for value, _ in tokens]) + self.assertNotIn("require", [value for value, _ in tokens]) + + def test_elf32_64_endianness_and_loader_hints_never_establish_mitigation(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "node.elf" + for bits in [32, 64]: + for endian in ["<", ">"]: + for kind, interpreter, layout, libc in [ + (3, b"/lib/ld-linux.so.2\0", "dynamic_executable_candidate", "glibc_loader_candidate"), + (2, b"/lib/ld-musl-x86_64.so.1\0", "fixed_address_executable_candidate", "musl_loader_candidate"), + (3, None, "shared_or_static_pie_unknown", "unknown"), + ]: + path.write_bytes(elf_fixture(bits, endian, kind, interpreter)) + result = c.inspect_elf(path) + self.assertEqual((bits, layout, libc), (result["class"], result["layout"], result["libc"])) + code, out, err = self.cli("--node-elf", str(path), "--evidence-root", directory) + self.assertEqual((0, ""), (code, err)) + row = json.loads(out)["results"][0] + self.assertEqual("unknown", row["status"]) + self.assertEqual("unknown", row["mitigation"]["state"]) + self.assertEqual("not_tested", row["exploitability"]) + self.assertNotIn(directory, out) + self.assertNotIn("/lib/ld-", out) + + def test_malformed_and_excessive_elf_headers_reject_before_output(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "input.elf" + cases = [b"", b"not ELF", elf_fixture()[:50], elf_fixture()[:-1], elf_fixture(interpreter=b"no-null")] + base = bytearray(elf_fixture()) + excessive = bytearray(base) + struct.pack_into("