diff --git a/.agents/skills/reverse-engineer-anything/SKILL.md b/.agents/skills/reverse-engineer-anything/SKILL.md index 790ece2995e..3aa007afd37 100644 --- a/.agents/skills/reverse-engineer-anything/SKILL.md +++ b/.agents/skills/reverse-engineer-anything/SKILL.md @@ -116,7 +116,10 @@ explicit path or endpoint and do not need it. - Android APK code, classes, methods, or incoming references: `inspect_android_package`, then focused Android tools when advertised. Archive member inventory still uses the archive route above. -- Managed PE/CLI assembly: `inspect_managed_artifact`. +- Managed PE/CLI assembly: `inspect_managed_artifact`. One that embeds + manifest resources also inventories them with `inspect_artifact` as + `dotnet-assembly`; extract a `.g.resources` member and inspect it as a + resource set. - .NET resource set (`.resources`, such as a WPF assembly's `.g.resources` holding BAML): `inspect_artifact` without a provider, then `extract_artifact` for selected members. Serialized objects are listed by diff --git a/.agents/skills/reverse-engineer-anything/references/native-and-artifacts.md b/.agents/skills/reverse-engineer-anything/references/native-and-artifacts.md index 62241c6dae4..2d044cf34ce 100644 --- a/.agents/skills/reverse-engineer-anything/references/native-and-artifacts.md +++ b/.agents/skills/reverse-engineer-anything/references/native-and-artifacts.md @@ -872,7 +872,13 @@ objects keep `value_kind: "serialized"` and `user_type_name` and are never deserialized; do not claim their contents. `name_hash_matches` false or root `name_hashes_sorted` false means runtime lookups by name fail. Use `extract_artifact` with occurrence IDs to write selected members; names that -collide as paths extract one at a time. See +collide as paths extract one at a time. + +A managed assembly whose CLI header declares a Resources directory +inventories as `dotnet-assembly`: each embedded ManifestResource is a member +holding its stored bytes, and linked resources are named in root metadata only. +Extract `.g.resources` from it, then inspect that file as a resource +set. See [.NET resource sets](https://github.com/morluto/rea/blob/main/docs/guides/managed/dotnet-resources.md). ### .NET NativeAOT diff --git a/.cursor-plugin/skills/reverse-engineer-anything/SKILL.md b/.cursor-plugin/skills/reverse-engineer-anything/SKILL.md index 790ece2995e..3aa007afd37 100644 --- a/.cursor-plugin/skills/reverse-engineer-anything/SKILL.md +++ b/.cursor-plugin/skills/reverse-engineer-anything/SKILL.md @@ -116,7 +116,10 @@ explicit path or endpoint and do not need it. - Android APK code, classes, methods, or incoming references: `inspect_android_package`, then focused Android tools when advertised. Archive member inventory still uses the archive route above. -- Managed PE/CLI assembly: `inspect_managed_artifact`. +- Managed PE/CLI assembly: `inspect_managed_artifact`. One that embeds + manifest resources also inventories them with `inspect_artifact` as + `dotnet-assembly`; extract a `.g.resources` member and inspect it as a + resource set. - .NET resource set (`.resources`, such as a WPF assembly's `.g.resources` holding BAML): `inspect_artifact` without a provider, then `extract_artifact` for selected members. Serialized objects are listed by diff --git a/.cursor-plugin/skills/reverse-engineer-anything/references/native-and-artifacts.md b/.cursor-plugin/skills/reverse-engineer-anything/references/native-and-artifacts.md index 62241c6dae4..2d044cf34ce 100644 --- a/.cursor-plugin/skills/reverse-engineer-anything/references/native-and-artifacts.md +++ b/.cursor-plugin/skills/reverse-engineer-anything/references/native-and-artifacts.md @@ -872,7 +872,13 @@ objects keep `value_kind: "serialized"` and `user_type_name` and are never deserialized; do not claim their contents. `name_hash_matches` false or root `name_hashes_sorted` false means runtime lookups by name fail. Use `extract_artifact` with occurrence IDs to write selected members; names that -collide as paths extract one at a time. See +collide as paths extract one at a time. + +A managed assembly whose CLI header declares a Resources directory +inventories as `dotnet-assembly`: each embedded ManifestResource is a member +holding its stored bytes, and linked resources are named in root metadata only. +Extract `.g.resources` from it, then inspect that file as a resource +set. See [.NET resource sets](https://github.com/morluto/rea/blob/main/docs/guides/managed/dotnet-resources.md). ### .NET NativeAOT diff --git a/docs/getting-started/cli.md b/docs/getting-started/cli.md index 39a47c1273f..c43459e95a6 100644 --- a/docs/getting-started/cli.md +++ b/docs/getting-started/cli.md @@ -274,10 +274,13 @@ names in a Unity `global-metadata.dat`, use analysis. See the [managed-code guide](../guides/managed/managed-code-analysis.md) for supported deployment forms, selection semantics, and coverage limits. -A `.resources` file, such as a WPF assembly's `.g.resources` with its BAML -documents, is an artifact: inventory its named resources and extract them. +A managed assembly that embeds resources inventories them as +`dotnet-assembly` members. A `.resources` file extracted from it, such as a +WPF assembly's `.g.resources` with its BAML documents, is an artifact too: +inventory its named resources and extract them. ```bash +rea extract-artifact /absolute/path/App.exe --output-root /absolute/path/assembly --json rea inspect-artifact /absolute/path/App.g.resources --json rea extract-artifact /absolute/path/App.g.resources --output-root /absolute/path/resources --json ``` diff --git a/docs/guides/managed/dotnet-resources.md b/docs/guides/managed/dotnet-resources.md index db62c88d535..6af078be4f0 100644 --- a/docs/guides/managed/dotnet-resources.md +++ b/docs/guides/managed/dotnet-resources.md @@ -1,5 +1,47 @@ # .NET resource sets +## Resources embedded in an assembly + +A managed assembly keeps its embedded resources, including a WPF assembly's +`.g.resources`, in the CLI Resources directory. When the CLI header +declares that directory and the file carries no other package, such as a .NET +single-file bundle, `rea inspect-artifact App.exe --json` or MCP +`inspect_artifact` inventories the file as `dotnet-assembly`: each +ManifestResource row embedded in the directory is a member whose bytes follow +its 4-byte length prefix. Nothing is decoded. A PE without a CLI header, or one +whose CLI header declares no Resources directory, stays a `pe` root. + +Each member records `resource_name`, its metadata `token`, `flags` and +`visibility`, and `declared_offset` within the directory. Root metadata counts +`resource_count` and `embedded_count`, records the directory's file range and +names each linked resource (one whose rows name another file or assembly) with +its implementation token; a linked resource's bytes are not in the module. +Resources that overrun the directory, names that are not safe paths and repeated +names are omitted and counted in the coverage limitations, and coverage is +then unknown. Managed inspection still leads the next probes; extraction +follows. + +```sh +rea extract-artifact App.exe --output-root /absolute/output --json +rea inspect-artifact /absolute/output/App.g.resources --json +``` + +Reader admission uses `artifact_limits.dotnet_assembly`: + +- `resource_count`: the ManifestResource rows; 100,000 by default and backed by + the session's `artifact.member_count` unless the call selects it. +- `metadata_bytes`: 64 MiB of CLI metadata read to list the rows. +- `representation_bytes`: 64 MiB of decoded rows and names. +- `retained_name_bytes`: 16 MiB of listed names, counting a name again for + every row that shares it. + +A refusal names the field and, where it is known, the required value; retry +with that field raised. A row whose name cannot be read is skipped and counted, +and coverage is then unknown. Resource bytes are served from the file and are +not read into memory. + +## Resource set files + Use `rea inspect-artifact Strings.resources --json` or MCP `inspect_artifact` to inventory a `.resources` stream, the format `ResourceWriter` and `resgen` produce and `ResourceManager` reads. Recognition uses the `0xBEEFCACE` magic diff --git a/docs/reference/limits-and-recovery.md b/docs/reference/limits-and-recovery.md index e98518164f7..7df2bf1f25c 100644 --- a/docs/reference/limits-and-recovery.md +++ b/docs/reference/limits-and-recovery.md @@ -844,7 +844,7 @@ editable setting or active worker telemetry. ## Artifact reader admission `inspect_artifact` and `extract_artifact` accept `bun`, `dotnet_bundle`, -`node_sea`, `godot`, `iso9660`, `deno`, `wxapkg`, `ar`, `dotnet_resources`, `tar` and +`node_sea`, `godot`, `iso9660`, `deno`, `wxapkg`, `ar`, `dotnet_assembly`, `dotnet_resources`, `tar` and `android_sparse_image`, `android_super_image`, `android_vbmeta`, `media_asset`, `android_dtbo` and `kubernetes_audit_log` groups in `artifact_limits`. Their controls apply when @@ -905,7 +905,7 @@ runtime override. See 100,000, range 1 to 2,147,483,647) is the session default for the per-call member counts `bun.module_count`, `dotnet_bundle.entry_count`, `node_sea.asset_count`, `deno.vfs_entries`, `zip.member_count`, `ar.header_count`, and -`dotnet_resources.resource_count`. An explicit `artifact_limits` +`dotnet_resources.resource_count` and `dotnet_assembly.resource_count`. An explicit `artifact_limits` field wins for that call; otherwise the runtime override, then the launch seed, then the default applies (see [precedence](#precedence-and-lifetime)). A refusal at one of those fields also reports `details.limit` as that diff --git a/docs/reference/mcp-contracts.md b/docs/reference/mcp-contracts.md index da1f87b4292..9670b22916d 100644 --- a/docs/reference/mcp-contracts.md +++ b/docs/reference/mcp-contracts.md @@ -2230,7 +2230,7 @@ when both are omitted, storage is not compared. UBI volumes (`ubi-volume`), ESP image segments (`esp-image-segment`), DfuSe elements (`dfuse-element`), ESP flash partitions (`esp-flash-partition`), Nintendo DS ROM members (`nds-entry`), FIT images (`fit-image`), SWF binary data (`swf-binary-data`), Unix ar members (`ar-entry`), -.NET resource set entries (`dotnet-resources-entry`), +.NET resource set entries (`dotnet-resources-entry`), .NET assembly manifest resources (`dotnet-assembly-resource`), MetaTrader program resources (`mql-program-entry`) and tar members (`tar-entry`); each format's guide names the compared fields. A changed declaration is a metadata change, including when content is unavailable. A declaration that diff --git a/docs/reference/supported-targets.md b/docs/reference/supported-targets.md index bf663acbb43..206635424f2 100644 --- a/docs/reference/supported-targets.md +++ b/docs/reference/supported-targets.md @@ -17,6 +17,7 @@ For worked examples by target type, see the [guides on rea.tools](https://rea.to | tar archives | Member inventory and extraction for stored and gzip tar, including `.unitypackage` | Built-in static ustar, pax and GNU headers; [tar archives](../tar-archives.md) | | Unix ar archives | GNU and BSD member inventory, thin references, and stored-member extraction | Built-in static reader; [Unix ar archives](../guides/artifacts/ar-archives.md) | | .NET resource sets | Named strings, byte arrays, streams and primitives with decoded values; serialized objects listed by type | Built-in static reader; [.NET resource sets](../guides/managed/dotnet-resources.md) | +| .NET assembly resources | Manifest resources embedded in a managed assembly, listed and extracted as stored bytes | Built-in static reader; [.NET resource sets](../guides/managed/dotnet-resources.md) | | Switch NSO/NRO | Module id, segment layout and hashes, NRO icon/NACP/RomFS ranges; LZ4 segments decompressed | Built-in static header parsing; [Switch executables](../guides/firmware/switch-executables.md) | | GPU asset headers | DDS (incl. DX10), GLB, KTX and KTX2 header facts and declared regions; payloads not decoded | Built-in static header parsing; [GPU asset headers](../gpu-asset-headers.md) | | Media asset headers | Ogg Opus, RIFF/XMA2, Bink 2 and Vulkan pipeline-cache header facts and declared regions; payloads not decoded | Built-in static header parsing; [media asset headers](../media-asset-headers.md) | diff --git a/scripts/ci/scopes.mjs b/scripts/ci/scopes.mjs index 7919c33a63d..762779731e5 100644 --- a/scripts/ci/scopes.mjs +++ b/scripts/ci/scopes.mjs @@ -174,6 +174,10 @@ const PATH_SCOPES = { "src/domain/mqlProgram*.ts", "docs/guides/artifacts/mql-programs.md", "src/artifacts/DotnetResourcesArtifactReader*.ts", + "src/artifacts/DotnetAssemblyArtifactReader*.ts", + "src/artifacts/dotnet/ManagedImageLocation*.ts", + "src/domain/formatMetadata/dotnetAssemblyMetadata.ts", + "tests/boundary/providers/native/artifactProvider.dotnetAssembly.test.ts", "src/domain/managed/dotnetResources*.ts", "src/domain/formatMetadata/dotnetResourcesMetadata.ts", "docs/guides/managed/dotnet-resources.md", diff --git a/src/artifacts/ArtifactEmbeddedFormatProbes.ts b/src/artifacts/ArtifactEmbeddedFormatProbes.ts index 531b9840c15..1b3c742ae64 100644 --- a/src/artifacts/ArtifactEmbeddedFormatProbes.ts +++ b/src/artifacts/ArtifactEmbeddedFormatProbes.ts @@ -19,6 +19,11 @@ import { sameRegularFileState, } from "../filesystem/RegularFile.js"; import { findDotnetBundleHeader } from "./dotnet/DotnetBundle.js"; +import { + locateManagedImage, + type ManagedImageLocationResult, +} from "./dotnet/ManagedImageLocation.js"; +import { readFileHandleRange } from "../filesystem/readFileHandleRange.js"; import { ArtifactReaderFailure, abortIfNeeded } from "../resources/index.js"; import { locateGodotPck, type GodotPckLocation } from "./GodotPckLocation.js"; import { @@ -48,6 +53,7 @@ export interface ArtifactEmbeddedFormatProbeFacts { readonly nodeSea?: NodeSeaLocation | null; readonly nodeSeaRecognitionFailure?: ArtifactReaderFailure; readonly dotnetBundleHeaderOffset?: number | null; + readonly managedImage?: ManagedImageLocationResult; readonly pyInstaller?: PyInstallerCookieObservation; } @@ -171,6 +177,25 @@ export class ArtifactEmbeddedFormatProbes { return header; } + /** Where a managed PE keeps its metadata and embedded resources. */ + async managedImage(): Promise { + abortIfNeeded(this.signal); + if (this.#facts.managedImage !== undefined) return this.#facts.managedImage; + const observed = await locateManagedImage( + (offset, length) => + readFileHandleRange( + this.source.handle, + offset, + Math.max(0, Math.min(length, this.source.initial.size - offset)), + () => abortIfNeeded(this.signal), + ), + this.source.initial.size, + ); + abortIfNeeded(this.signal); + this.#facts = { ...this.#facts, managedImage: observed }; + return observed; + } + async bunStandalone(): Promise { abortIfNeeded(this.signal); if (this.#facts.bunStandalone !== undefined) diff --git a/src/artifacts/ArtifactReaderAdmission.ts b/src/artifacts/ArtifactReaderAdmission.ts index ffbb0ff404f..04e7c56d23b 100644 --- a/src/artifacts/ArtifactReaderAdmission.ts +++ b/src/artifacts/ArtifactReaderAdmission.ts @@ -5,6 +5,7 @@ import type { NodeSeaAdmission } from "./nodeSea/NodeSeaAdmission.js"; import type { PyInstallerAdmission } from "./pyinstaller/PyInstallerAdmission.js"; import type { BunStandaloneAdmission } from "./bun/BunStandaloneAdmission.js"; import type { DenoStandaloneAdmission } from "./deno/DenoStandaloneAdmission.js"; +import type { DotnetAssemblyAdmission } from "./dotnet/DotnetAssemblyAdmission.js"; import type { DotnetBundleAdmission } from "./dotnet/DotnetBundleAdmission.js"; import type { EspFlashAdmission } from "./EspFlashImageArtifactReader.js"; @@ -15,6 +16,7 @@ export type ArtifactFormatAdmission = | NodeSeaAdmission | PyInstallerAdmission | DotnetBundleAdmission + | DotnetAssemblyAdmission | BunStandaloneAdmission | DenoStandaloneAdmission | EspFlashAdmission; diff --git a/src/artifacts/DotnetAssemblyArtifactReader.test.ts b/src/artifacts/DotnetAssemblyArtifactReader.test.ts new file mode 100644 index 00000000000..a82c7f27a2f --- /dev/null +++ b/src/artifacts/DotnetAssemblyArtifactReader.test.ts @@ -0,0 +1,299 @@ +import { buffer } from "node:stream/consumers"; +import { expect, it } from "vitest"; +import { createTestTempFile } from "../../tests/fixtures/temporaryDirectory.js"; +import { + DEFAULT_DOTNET_ASSEMBLY_READER_LIMITS, + type DotnetAssemblyReaderLimits, +} from "../domain/artifactReaderLimits.js"; +import { + buildManagedPeFixture, + buildNativePeFixture, +} from "../dotnet/ManagedPe.fixture.js"; +import { openRegularFile } from "../filesystem/RegularFile.js"; +import type { + ArtifactEntry, + ArtifactReaderTraversal, +} from "../resources/index.js"; +import { DotnetAssemblyArtifactReader } from "./DotnetAssemblyArtifactReader.js"; + +const inspect = async ( + bytes: Buffer, + limits?: Partial, +) => { + const path = await createTestTempFile( + "rea-dotnet-assembly-", + "App.dll", + bytes, + ); + const reader = new DotnetAssemblyArtifactReader(path, undefined, { + ...DEFAULT_DOTNET_ASSEMBLY_READER_LIMITS, + ...limits, + }); + const entries: ArtifactEntry[] = []; + const coverage: ArtifactReaderTraversal[] = []; + try { + let failure: unknown; + try { + for await (const entry of reader.entries(undefined, { + onCoverage: (value) => coverage.push(value), + })) + entries.push(entry); + } catch (cause) { + failure = cause; + } + const contents = new Map(); + for (const entry of entries) + contents.set(entry.path, await buffer(await reader.open(entry))); + return { + entries, + failure, + coverage, + contents, + metadata: reader.formatMetadata(), + }; + } finally { + await reader.close(); + } +}; + +/** The fixture's CLI header: size 72, runtime 2.5, metadata at RVA 0x2100. */ +const cliHeader = (bytes: Buffer): number => + bytes.indexOf(Buffer.of(72, 0, 0, 0, 2, 0, 5, 0, 0, 0x21, 0, 0)); + +it("lists an embedded manifest resource as its stored bytes", async () => { + const data = Buffer.from("resource payload"); + const result = await inspect(buildManagedPeFixture({ resourceData: data })); + expect(result.failure).toBeUndefined(); + expect(result.coverage).toEqual([{ status: "complete", limitations: [] }]); + expect(result.entries).toHaveLength(1); + expect(result.entries[0]).toMatchObject({ + path: "Fixture.resources", + kind: "file", + declaredSize: data.length, + executable: null, + formatMetadata: { + kind: "dotnet-assembly-resource", + resource_name: "Fixture.resources", + token: "0x28000001", + visibility: "private", + declared_offset: 0, + }, + }); + expect(result.contents.get("Fixture.resources")?.equals(data)).toBe(true); + expect(result.metadata).toMatchObject({ + kind: "dotnet-assembly", + resource_count: 1, + embedded_count: 1, + linked_resources: [], + resources_directory: { size: 4 + data.length }, + }); +}); + +it("names a linked resource without listing bytes it does not hold", async () => { + // Implementation coded index: AssemblyRef (tag 1), row 1. + const result = await inspect( + buildManagedPeFixture({ + resourceImplementationRaw: (1 << 2) | 1, + references: ["Satellite"], + }), + ); + expect(result.entries).toEqual([]); + expect(result.metadata).toMatchObject({ + resource_count: 1, + embedded_count: 0, + linked_resources: [ + { + resource_name: "Fixture.resources", + token: "0x28000001", + implementation_token: "0x23000001", + }, + ], + }); + expect(result.coverage).toEqual([ + { + status: "complete", + limitations: [ + "1 manifest resource(s) are linked from another file or assembly; their bytes are not in this module.", + ], + }, + ]); +}); + +it("skips a resource whose length overruns the Resources directory", async () => { + const bytes = buildManagedPeFixture({ resourceData: Buffer.from("abc") }); + const cli = cliHeader(bytes); + // Shrink the directory below the resource it declares. + bytes.writeUInt32LE(5, cli + 28); + const result = await inspect(bytes); + expect(result.entries).toEqual([]); + expect(result.coverage).toEqual([ + { + status: "unknown", + limitations: [ + "1 embedded resource(s) lie outside the CLI Resources directory.", + ], + }, + ]); +}); + +it("lists nothing when the CLI header declares no Resources directory", async () => { + const bytes = buildManagedPeFixture(); + const cli = cliHeader(bytes); + bytes.writeUInt32LE(0, cli + 24); + bytes.writeUInt32LE(0, cli + 28); + const result = await inspect(bytes); + expect(result.entries).toEqual([]); + expect(result.metadata).toMatchObject({ resources_directory: null }); + expect(result.coverage[0]?.status).toBe("unknown"); +}); + +it("refuses resource rows or metadata over their limits", async () => { + const bytes = buildManagedPeFixture(); + const count = await inspect(bytes, { resource_count: 0 }); + expect(count.failure).toMatchObject({ + reason: "limit", + readerLimit: { + parameter: "artifact_limits.dotnet_assembly.resource_count", + effective_value: 0, + required_value: 1, + unit: "count", + }, + }); + const metadata = await inspect(bytes, { metadata_bytes: 16 }); + expect(metadata.failure).toMatchObject({ + reason: "limit", + readerLimit: { + parameter: "artifact_limits.dotnet_assembly.metadata_bytes", + effective_value: 16, + unit: "bytes", + }, + }); +}); + +it("refuses a file that is not a managed image", async () => { + const result = await inspect(buildNativePeFixture()); + expect(result.failure).toMatchObject({ reason: "unsupported" }); +}); + +it("counts a row whose implementation index is invalid once", async () => { + // Implementation tag 3 names no table. + const result = await inspect( + buildManagedPeFixture({ resourceImplementationRaw: 3 }), + ); + expect(result.entries).toEqual([]); + expect(result.coverage).toEqual([ + { + status: "unknown", + limitations: [ + "1 manifest resource row(s) have an invalid implementation index.", + ], + }, + ]); +}); + +it("lists every embedded resource in its directory range", async () => { + const result = await inspect( + buildManagedPeFixture({ + resourceData: Buffer.from("first"), + extraResources: [ + { name: "App.g.resources", data: Buffer.from("second!") }, + { name: "Strings.resources", data: Buffer.alloc(0) }, + ], + }), + ); + expect(result.coverage[0]?.status).toBe("complete"); + expect( + Object.fromEntries( + [...result.contents].map(([path, bytes]) => [path, bytes.toString()]), + ), + ).toEqual({ + "Fixture.resources": "first", + "App.g.resources": "second!", + "Strings.resources": "", + }); +}); + +it("names its own controls for the decode budget and retained names", async () => { + const bytes = buildManagedPeFixture(); + const budget = await inspect(bytes, { representation_bytes: 1 }); + expect(budget.failure).toMatchObject({ + reason: "limit", + readerLimit: { + parameter: "artifact_limits.dotnet_assembly.representation_bytes", + effective_value: 1, + unit: "bytes", + }, + }); + const names = await inspect( + buildManagedPeFixture({ + extraResources: [{ name: "Second.resources", data: Buffer.of(1) }], + }), + { retained_name_bytes: 20 }, + ); + expect(names.entries).toEqual([]); + expect(names.failure).toMatchObject({ + reason: "limit", + readerLimit: { + parameter: "artifact_limits.dotnet_assembly.retained_name_bytes", + effective_value: 20, + // "Fixture.resources" and "Second.resources" are 17 and 16 bytes. + required_value: 33, + unit: "bytes", + }, + }); +}); + +it("skips a row whose name cannot be read and keeps the others", async () => { + const bytes = buildManagedPeFixture({ + extraResources: [{ name: "Kept.resources", data: Buffer.from("kept") }], + }); + // Make the first row's name invalid UTF-8 in the string heap. + bytes[bytes.indexOf(Buffer.from("Fixture.resources"))] = 0xff; + const result = await inspect(bytes); + expect(result.failure).toBeUndefined(); + expect(result.entries.map(({ path }) => path)).toEqual(["Kept.resources"]); + expect(result.contents.get("Kept.resources")?.toString()).toBe("kept"); + expect(result.metadata).toMatchObject({ resource_count: 2 }); + expect(result.coverage).toEqual([ + { + status: "unknown", + limitations: [ + "1 manifest resource row(s) cannot be read and were skipped.", + ], + }, + ]); +}); + +it("reads the directories classification located for the same file", async () => { + const bytes = buildManagedPeFixture(); + const path = await createTestTempFile( + "rea-dotnet-assembly-", + "App.dll", + bytes, + ); + const source = await openRegularFile(path, { symlinks: "reject" }); + const cli = cliHeader(bytes); + const metadata = { + offset: bytes.indexOf(Buffer.from("BSJB")), + size: bytes.readUInt32LE(cli + 12), + }; + // An admission without a Resources directory proves the reader does not + // locate the directories again. + const reader = new DotnetAssemblyArtifactReader(path, { + kind: "dotnet-assembly", + source, + location: { metadata, resources: null }, + }); + try { + const entries: ArtifactEntry[] = []; + for await (const entry of reader.entries()) entries.push(entry); + expect(entries).toEqual([]); + expect(reader.formatMetadata()).toMatchObject({ + embedded_count: 1, + resources_directory: null, + }); + } finally { + await reader.close(); + await source.handle.close(); + } +}); diff --git a/src/artifacts/DotnetAssemblyArtifactReader.ts b/src/artifacts/DotnetAssemblyArtifactReader.ts new file mode 100644 index 00000000000..84969495184 --- /dev/null +++ b/src/artifacts/DotnetAssemblyArtifactReader.ts @@ -0,0 +1,356 @@ +import { + DEFAULT_DOTNET_ASSEMBLY_READER_LIMITS, + type DotnetAssemblyReaderLimits, +} from "../domain/artifactReaderLimits.js"; +import { BinaryReader } from "../domain/binaryContainer.js"; +import type { + DotnetAssemblyMetadata, + DotnetAssemblyResourceMetadata, +} from "../domain/formatMetadata/dotnetAssemblyMetadata.js"; +import { readManagedMetadataLayout } from "../domain/managed/managedMetadataLayout.js"; +import { + readManifestResourceRow, + type ManifestResourceRow, +} from "../domain/managed/managedMetadataInventoryRows.js"; +import { ManagedRepresentationFailure } from "../domain/managed/managedDecodeBudget.js"; +import { + ManagedReaderFailure, + managedIssueTargetFailure, + readManagedValue, +} from "../domain/managed/managedReaderFailure.js"; +import type { ManagedParseIssue } from "../domain/managed/managedArtifact.js"; +import type { StableRegularFileDescriptor } from "../filesystem/RegularFile.js"; +import { + ArtifactReaderFailure, + artifactFormatFailure, + artifactReaderLimitFailure, + malformedArtifact, + normalizeArtifactPath, + unsupportedArtifact, + type ArtifactEntry, +} from "../resources/index.js"; +import { + createBoundedArtifactRead, + createExactArtifactRead, +} from "./ArtifactFileRange.js"; +import { + PositionalArtifactReader, + type PositionalArtifactEntries, +} from "./PositionalArtifactReader.js"; +import type { DotnetAssemblyAdmission } from "./dotnet/DotnetAssemblyAdmission.js"; +import { + locateManagedImage, + type FileRange, + type ManagedImageLocationResult, +} from "./dotnet/ManagedImageLocation.js"; + +/** ManifestResource is metadata table 0x28. */ +const MANIFEST_RESOURCE_TABLE = 40; +/** Length prefixes are read through windows of the Resources directory this large. */ +const LENGTH_WINDOW_BYTES = 64 * 1024; + +type Read = (offset: number, length: number) => Promise; + +/** A resource name as a logical path, or null when it is not a safe path. */ +const logicalResourcePath = (name: string): string | null => { + try { + return normalizeArtifactPath(name); + } catch (cause: unknown) { + if (!(cause instanceof ArtifactReaderFailure) || cause.reason !== "path") + throw cause; + return null; + } +}; + +/** The managed reader's refusal as this format's failure. */ +const managedFailure = ( + cause: ManagedReaderFailure, + representationBytes: number, +): ArtifactReaderFailure => { + // The decode budget is this group's control, so a retry can raise it. + if (cause instanceof ManagedRepresentationFailure) + return artifactReaderLimitFailure( + "artifact_limits.dotnet_assembly.representation_bytes", + representationBytes, + "bytes", + ); + const failure = managedIssueTargetFailure(cause.issue); + return failure === undefined + ? new ArtifactReaderFailure("limit", cause.message, { + cause, + boundary: "memory", + }) + : artifactFormatFailure(failure, { cause }); +}; + +/** Read each embedded resource's 4-byte length prefix, in directory order. */ +const readLengthPrefixes = async ( + read: Read, + directory: FileRange, + rows: readonly ManifestResourceRow[], +): Promise> => { + const lengths = new Map(); + let start = 0; + let window: BinaryReader | undefined; + for (const row of [...rows].sort( + (left, right) => left.declaredOffset - right.declaredOffset, + )) { + const at = row.declaredOffset; + if (at > directory.size - 4) continue; + if ( + window === undefined || + at < start || + at + 4 > start + window.bytes.length + ) { + start = at; + window = new BinaryReader( + await read( + directory.offset + at, + Math.min(directory.size - at, LENGTH_WINDOW_BYTES), + ), + true, + "dotnet-assembly", + ); + } + lengths.set(row, window.u32(at - start)); + } + return lengths; +}; + +/** + * Lists the resources a managed assembly embeds in its CLI Resources + * directory, such as a WPF assembly's `.g.resources`. Each member is + * the stored resource bytes after their length prefix; nothing is decoded. + */ +export class DotnetAssemblyArtifactReader extends PositionalArtifactReader< + DotnetAssemblyMetadata, + ArtifactEntry +> { + override readonly format = "dotnet-assembly" as const; + /** Classification's location for the same descriptor, used once. */ + #admitted: ManagedImageLocationResult | undefined; + + constructor( + path: string, + admitted?: StableRegularFileDescriptor | DotnetAssemblyAdmission, + private readonly limits: DotnetAssemblyReaderLimits = DEFAULT_DOTNET_ASSEMBLY_READER_LIMITS, + ) { + super( + path, + ".NET assembly", + admitted !== undefined && "kind" in admitted ? admitted.source : admitted, + ); + if (admitted !== undefined && "kind" in admitted) + this.#admitted = { state: "located", location: admitted.location }; + } + + formatMetadata(): DotnetAssemblyMetadata | undefined { + return this.snapshotMetadata((metadata) => ({ + ...metadata, + linked_resources: metadata.linked_resources.map((row) => ({ ...row })), + })); + } + + protected override async prepareEntries( + signal?: AbortSignal, + ): Promise> { + const { handle, initial } = await this.verifyCarrier(signal); + const fileSize = initial.size; + const located = + this.#admitted ?? + (await locateManagedImage( + createBoundedArtifactRead(this.format, handle, fileSize, signal), + fileSize, + )); + this.#admitted = undefined; + this.assertOpen(signal); + if (located.state === "absent") + throw unsupportedArtifact( + this.format, + "The file is not a managed PE image with a CLI header", + ); + if (located.state === "malformed") + throw malformedArtifact(this.format, located.reason, { + field: "cli-header", + }); + const { metadata, resources } = located.location; + if (metadata.size > this.limits.metadata_bytes) + throw artifactReaderLimitFailure( + "artifact_limits.dotnet_assembly.metadata_bytes", + this.limits.metadata_bytes, + "bytes", + metadata.size, + ); + const read = createExactArtifactRead(this.format, handle, fileSize, signal); + const bytes = await read(metadata.offset, metadata.size); + this.assertOpen(signal); + + // Row issues are counted below, not listed one by one. + const issues: ManagedParseIssue[] = []; + const rows: ManifestResourceRow[] = []; + let rowCount: number; + let unreadableRows = 0; + try { + const layout = readManagedMetadataLayout( + bytes, + 0, + bytes.length, + this.limits.representation_bytes, + ); + rowCount = layout.table(MANIFEST_RESOURCE_TABLE)?.rowCount ?? 0; + if (rowCount > this.limits.resource_count) + throw artifactReaderLimitFailure( + "artifact_limits.dotnet_assembly.resource_count", + this.limits.resource_count, + "count", + rowCount, + ); + // A row whose name cannot be read is skipped; budgets still stop. + for (let row = 1; row <= rowCount; row += 1) { + const value = readManagedValue( + () => readManifestResourceRow(bytes, layout, row, issues), + issues, + ); + if (value === undefined) unreadableRows += 1; + else rows.push(value); + } + } catch (cause: unknown) { + if (cause instanceof ManagedReaderFailure) + throw managedFailure(cause, this.limits.representation_bytes); + throw cause; + } + + const embedded = rows.filter( + ({ implementation }) => implementation.kind === "null", + ); + const linked = rows.filter( + ({ implementation }) => implementation.kind === "valid", + ); + // Every row may repeat one cached name; each listed copy is output, so + // all of them count before anything is built. + const requiredNameBytes = [...embedded, ...linked].reduce( + (total, { name }) => total + Buffer.byteLength(name, "utf8"), + 0, + ); + if (requiredNameBytes > this.limits.retained_name_bytes) + throw artifactReaderLimitFailure( + "artifact_limits.dotnet_assembly.retained_name_bytes", + this.limits.retained_name_bytes, + "bytes", + requiredNameBytes, + ); + const lengths = + resources === null + ? new Map() + : await readLengthPrefixes(read, resources, embedded); + this.assertOpen(signal); + + const entries: ArtifactEntry[] = []; + const paths = new Set(); + let outOfRange = 0; + let unsafeNames = 0; + let duplicateNames = 0; + for (const row of embedded) { + const length = lengths.get(row); + const payload = row.declaredOffset + 4; + if ( + resources === null || + length === undefined || + length > resources.size - payload + ) { + outOfRange += 1; + continue; + } + const path = logicalResourcePath(row.name); + if (path === null) { + unsafeNames += 1; + continue; + } + if (paths.has(path)) { + duplicateNames += 1; + continue; + } + paths.add(path); + const formatMetadata: DotnetAssemblyResourceMetadata = { + kind: "dotnet-assembly-resource", + resource_name: row.name, + token: row.token, + flags: row.flags, + visibility: row.visibility, + declared_offset: row.declaredOffset, + }; + entries.push({ + path, + kind: "file", + declaredSize: length, + compressedSize: null, + // A manifest resource records no permission bits. + executable: null, + encrypted: false, + byteOffset: resources.offset + payload, + declaredIntegrity: null, + unpacked: false, + limitations: [], + adapterKey: `dotnet-assembly:${row.token}`, + formatMetadata, + }); + } + + const invalidRows = rows.length - embedded.length - linked.length; + const limitations: string[] = []; + if (linked.length > 0) + limitations.push( + `${String(linked.length)} manifest resource(s) are linked from another file or assembly; their bytes are not in this module.`, + ); + if (unreadableRows > 0) + limitations.push( + `${String(unreadableRows)} manifest resource row(s) cannot be read and were skipped.`, + ); + if (invalidRows > 0) + limitations.push( + `${String(invalidRows)} manifest resource row(s) have an invalid implementation index.`, + ); + if (outOfRange > 0) + limitations.push( + `${String(outOfRange)} embedded resource(s) lie outside the CLI Resources directory.`, + ); + if (unsafeNames > 0) + limitations.push( + `${String(unsafeNames)} resource name(s) cannot be represented as safe paths.`, + ); + if (duplicateNames > 0) + limitations.push( + `${String(duplicateNames)} resource name(s) repeat an earlier name; only the first is listed.`, + ); + + return { + entries, + coverage: { + status: + unreadableRows + + invalidRows + + outOfRange + + unsafeNames + + duplicateNames === + 0 + ? "complete" + : "unknown", + limitations, + }, + formatMetadata: { + kind: "dotnet-assembly", + resource_count: rowCount, + embedded_count: embedded.length, + linked_resources: linked.map((row) => ({ + resource_name: row.name, + token: row.token, + implementation_token: + row.implementation.kind === "valid" + ? row.implementation.token + : null, + })), + resources_directory: resources, + }, + }; + } +} diff --git a/src/artifacts/artifactFormats.ts b/src/artifacts/artifactFormats.ts index ffb8ad7213e..168a6e08768 100644 --- a/src/artifacts/artifactFormats.ts +++ b/src/artifacts/artifactFormats.ts @@ -83,6 +83,8 @@ import { SwitchExecutableArtifactReader } from "./SwitchExecutableArtifactReader import { UnityFsArtifactReader } from "./UnityFsArtifactReader.js"; import { WxapkgArtifactReader } from "./WxapkgArtifactReader.js"; import { ArArtifactReader } from "./ArArtifactReader.js"; +import { DotnetAssemblyArtifactReader } from "./DotnetAssemblyArtifactReader.js"; +import type { DotnetAssemblyAdmission } from "./dotnet/DotnetAssemblyAdmission.js"; import { DotnetResourcesArtifactReader } from "./DotnetResourcesArtifactReader.js"; import { TarArtifactReader } from "./tar/TarArtifactReader.js"; import { @@ -153,6 +155,10 @@ function admittedAs( kind: "asar", options: ArtifactReaderConstruction, ): AsarAdmission | ReturnType; +function admittedAs( + kind: "dotnet-assembly", + options: ArtifactReaderConstruction, +): DotnetAssemblyAdmission | ReturnType; function admittedAs( kind: "dotnet-bundle", options: ArtifactReaderConstruction, @@ -336,6 +342,18 @@ const switchExecutable = (id: Id) => }); const NON_ZIP_FORMATS = { + "dotnet-assembly": container("dotnet-assembly", { + retainClassifiedSource: true, + absentInventory: "root", + readerLimitation: + ".NET assembly inventory lists each manifest resource embedded in the CLI Resources directory as its stored bytes; nothing is decoded, and linked resources are named but live in other files.", + createReader: (path, options) => + new DotnetAssemblyArtifactReader( + path, + admittedAs("dotnet-assembly", options), + options.readerLimits?.dotnet_assembly, + ), + }), "dotnet-bundle": container("dotnet-bundle", { retainClassifiedSource: true, absentInventory: "root", diff --git a/src/artifacts/dotnet/DotnetAssemblyAdmission.ts b/src/artifacts/dotnet/DotnetAssemblyAdmission.ts new file mode 100644 index 00000000000..108b87fe8a5 --- /dev/null +++ b/src/artifacts/dotnet/DotnetAssemblyAdmission.ts @@ -0,0 +1,9 @@ +import type { StableRegularFileDescriptor } from "../../filesystem/RegularFile.js"; +import type { ManagedImageLocation } from "./ManagedImageLocation.js"; + +/** The managed directories located in this unchanged, borrowed descriptor. */ +export interface DotnetAssemblyAdmission { + readonly kind: "dotnet-assembly"; + readonly source: StableRegularFileDescriptor; + readonly location: ManagedImageLocation; +} diff --git a/src/artifacts/dotnet/ManagedImageLocation.test.ts b/src/artifacts/dotnet/ManagedImageLocation.test.ts new file mode 100644 index 00000000000..3f2950f9657 --- /dev/null +++ b/src/artifacts/dotnet/ManagedImageLocation.test.ts @@ -0,0 +1,104 @@ +import { expect, it } from "vitest"; +import { + buildManagedPeFixture, + buildNativePeFixture, +} from "../../dotnet/ManagedPe.fixture.js"; +import { locateManagedImage } from "./ManagedImageLocation.js"; + +const locate = (bytes: Buffer) => + locateManagedImage( + async (offset, length) => + bytes.subarray(offset, Math.min(bytes.length, offset + length)), + bytes.length, + ); + +/** The fixture's CLI header: size 72, runtime 2.5, metadata at RVA 0x2100. */ +const cliHeader = (bytes: Buffer): number => + bytes.indexOf(Buffer.of(72, 0, 0, 0, 2, 0, 5, 0, 0, 0x21, 0, 0)); + +it("locates the metadata and the Resources directory from the headers", async () => { + const data = Buffer.from("embedded-bytes"); + const bytes = buildManagedPeFixture({ resourceData: data }); + const result = await locate(bytes); + if (result.state !== "located") throw new Error(result.state); + const { metadata, resources } = result.location; + expect(bytes.toString("latin1", metadata.offset, metadata.offset + 4)).toBe( + "BSJB", + ); + expect(resources?.size).toBe(4 + data.length); + expect(bytes.readUInt32LE(resources!.offset)).toBe(data.length); + expect( + bytes + .subarray(resources!.offset + 4, resources!.offset + 4 + data.length) + .equals(data), + ).toBe(true); +}); + +it("reports no Resources directory when the CLI header declares none", async () => { + const bytes = buildManagedPeFixture(); + const cli = cliHeader(bytes); + bytes.writeUInt32LE(0, cli + 24); + bytes.writeUInt32LE(0, cli + 28); + expect(await locate(bytes)).toMatchObject({ + state: "located", + location: { resources: null }, + }); +}); + +it("treats native PEs and other bytes as absent", async () => { + expect(await locate(buildNativePeFixture())).toEqual({ state: "absent" }); + expect(await locate(Buffer.alloc(256))).toEqual({ state: "absent" }); + expect(await locate(Buffer.from("MZ"))).toEqual({ state: "absent" }); +}); + +it("rejects a Resources directory that maps outside the image", async () => { + const bytes = buildManagedPeFixture(); + bytes.writeUInt32LE(0x7fff_0000, cliHeader(bytes) + 24); + expect(await locate(bytes)).toEqual({ + state: "malformed", + reason: "The CLI Resources directory cannot be mapped", + }); +}); + +it("rejects an unmappable metadata directory", async () => { + const bytes = buildManagedPeFixture(); + bytes.writeUInt32LE(0x7fff_0000, cliHeader(bytes) + 8); + expect(await locate(bytes)).toMatchObject({ state: "malformed" }); +}); + +it("rejects a Resources directory past the end of the file", async () => { + const bytes = buildManagedPeFixture(); + const located = await locate(bytes); + if (located.state !== "located") throw new Error(located.state); + const end = located.location.resources!.offset + 2; + expect(await locate(bytes.subarray(0, end))).toEqual({ + state: "malformed", + reason: "The CLI Resources directory cannot be mapped", + }); +}); + +it("rejects a CLI header that declares or holds fewer than 72 bytes", async () => { + const short = buildManagedPeFixture(); + short.writeUInt32LE(48, cliHeader(short)); + expect(await locate(short)).toEqual({ + state: "malformed", + reason: "The CLI header is truncated", + }); + const bytes = buildManagedPeFixture(); + const cut = bytes.subarray(0, cliHeader(bytes) + 40); + expect(await locate(cut)).toMatchObject({ state: "malformed" }); +}); + +it("requires the header's whole declared size inside the file", async () => { + const bytes = buildManagedPeFixture(); + const cli = cliHeader(bytes); + // PE32 data directory 14 (CLI header) holds its RVA and size. + const directory = bytes.readUInt32LE(0x3c) + 24 + 96 + 14 * 8; + bytes.writeUInt32LE(96, directory + 4); + bytes.writeUInt32LE(96, cli); + expect(await locate(bytes)).toMatchObject({ state: "located" }); + expect(await locate(bytes.subarray(0, cli + 80))).toEqual({ + state: "malformed", + reason: "The CLI header is truncated", + }); +}); diff --git a/src/artifacts/dotnet/ManagedImageLocation.ts b/src/artifacts/dotnet/ManagedImageLocation.ts new file mode 100644 index 00000000000..165d21e4fd5 --- /dev/null +++ b/src/artifacts/dotnet/ManagedImageLocation.ts @@ -0,0 +1,139 @@ +import { + parsePeRecordFacts, + peRvaToFileOffset, +} from "../../domain/binaryTarget.js"; +import { observeMzWindowsHeader } from "../../domain/dosMz.js"; +import { + MANAGED_CLI_HEADER_RESOURCES_PREFIX_BYTES, + readManagedCliHeaderPrefix, +} from "../../domain/managed/managedCliHeaderPrefix.js"; +import { readPeCoffHeader } from "../../domain/peCoffHeader.js"; + +/** The CLI header's data directory index in the PE optional header. */ +const CLI_DIRECTORY = 14; +/** IMAGE_COR20_HEADER is 72 bytes. */ +const CLI_HEADER_BYTES = 72; +/** An optional header larger than this is not a PE this reader admits. */ +const MAX_OPTIONAL_HEADER_BYTES = 4096; +/** The MZ header, through e_lfanew. */ +const MZ_PREFIX_BYTES = 64; + +export interface FileRange { + readonly offset: number; + readonly size: number; +} + +/** Where a managed image keeps its metadata and embedded resources. */ +export interface ManagedImageLocation { + readonly metadata: FileRange; + /** Null when the CLI header declares no Resources directory. */ + readonly resources: FileRange | null; +} + +export type ManagedImageLocationResult = + | { readonly state: "located"; readonly location: ManagedImageLocation } + /** A PE without a CLI header, or not a PE at all. */ + | { readonly state: "absent" } + /** A CLI header whose directories cannot be mapped to file ranges. */ + | { readonly state: "malformed"; readonly reason: string }; + +type Read = (offset: number, length: number) => Promise; + +/** + * Locate the metadata and Resources directory of a managed PE by reading + * only its headers, section table and CLI header. `read` must return the + * requested bytes, or fewer at the end of the file. + */ +export const locateManagedImage = async ( + read: Read, + fileSize: number, +): Promise => { + if (fileSize < MZ_PREFIX_BYTES) return { state: "absent" }; + const observed = observeMzWindowsHeader( + await read(0, MZ_PREFIX_BYTES), + fileSize, + ); + if (observed.state !== "signature-needed" && observed.state !== "declared") + return { state: "absent" }; + const peOffset = observed.offset; + const coff = await read(peOffset, Math.min(24, fileSize - peOffset)); + if (coff.length < 24 || coff.toString("latin1", 0, 4) !== "PE\0\0") + return { state: "absent" }; + const header = readPeCoffHeader(coff.subarray(4)); + if (!header.ok) return { state: "absent" }; + const { optionalHeaderSize, sectionCount } = header.value; + if (optionalHeaderSize > MAX_OPTIONAL_HEADER_BYTES) + return { state: "absent" }; + const optional = await read(peOffset + 24, optionalHeaderSize); + const parsed = parsePeRecordFacts(Buffer.concat([coff, optional]), undefined); + if (!parsed.ok || parsed.value.metadata.format !== "pe") + return { state: "absent" }; + if (!parsed.value.metadata.managed) return { state: "absent" }; + const cliDirectory = + parsed.value.optionalHeader.dataDirectories[CLI_DIRECTORY]; + if (cliDirectory === undefined) return { state: "absent" }; + + const sections = await read( + peOffset + 24 + optionalHeaderSize, + sectionCount * 40, + ); + const mapped = (rva: number, size: number): number | undefined => + peRvaToFileOffset( + rva, + sections, + sectionCount, + parsed.value.optionalHeader.sizeOfHeaders, + size, + ); + const cliOffset = mapped(cliDirectory.address, CLI_HEADER_BYTES); + if (cliOffset === undefined || cliDirectory.size < CLI_HEADER_BYTES) + return { state: "malformed", reason: "The CLI header cannot be mapped" }; + const cli = readManagedCliHeaderPrefix( + await read(cliOffset, MANAGED_CLI_HEADER_RESOURCES_PREFIX_BYTES), + ); + if ( + !cli.ok || + cli.value.resources === undefined || + cli.value.headerSize < CLI_HEADER_BYTES || + cli.value.headerSize > cliDirectory.size || + cliOffset + cli.value.headerSize > fileSize + ) + return { state: "malformed", reason: "The CLI header is truncated" }; + const metadataOffset = mapped( + cli.value.metadata.rva, + cli.value.metadata.size, + ); + // A section may declare raw data past the end of the file. + const inFile = (offset: number, size: number) => offset + size <= fileSize; + if ( + metadataOffset === undefined || + cli.value.metadata.size === 0 || + !inFile(metadataOffset, cli.value.metadata.size) + ) + return { + state: "malformed", + reason: "The CLI metadata directory cannot be mapped", + }; + const { rva, size } = cli.value.resources; + if (rva === 0 && size === 0) + return { + state: "located", + location: { + metadata: { offset: metadataOffset, size: cli.value.metadata.size }, + resources: null, + }, + }; + const resourcesOffset = mapped(rva, size); + if (resourcesOffset === undefined || !inFile(resourcesOffset, size)) + return { + state: "malformed", + reason: "The CLI Resources directory cannot be mapped", + }; + return { + state: "located", + location: { + metadata: { offset: metadataOffset, size: cli.value.metadata.size }, + resources: { offset: resourcesOffset, size }, + }, + }; +}; diff --git a/src/artifacts/extraction/ArtifactExtraction.ts b/src/artifacts/extraction/ArtifactExtraction.ts index c7c706645d0..29b85a003e5 100644 --- a/src/artifacts/extraction/ArtifactExtraction.ts +++ b/src/artifacts/extraction/ArtifactExtraction.ts @@ -1,6 +1,9 @@ import { selectArtifactExtractionOccurrences } from "./ArtifactExtractionSelection.js"; import type { ArtifactReaderLimits } from "../../domain/artifactReaderLimits.js"; -import { assertAdmittedRootDigest } from "../inventory/classify.js"; +import { + assertAdmittedRootDigest, + hasEmbeddedManagedResources, +} from "../inventory/classify.js"; import { InesArtifactReader } from "../InesArtifactReader.js"; import { locatesQualcommMbnHashSegment } from "../QualcommMbnLocation.js"; import { @@ -721,6 +724,7 @@ const requireExtractableFormat = async ( (await probes.godotPck()) !== undefined || ((format === "elf" || format === "pe" || format === "mach-o") && (await hasExecutablePack(probes))) || + (format === "pe" && (await hasEmbeddedManagedResources(probes))) || (format === "elf" && (await locatesQualcommMbnHashSegment( (offset, length) => diff --git a/src/artifacts/inventory/classify.ts b/src/artifacts/inventory/classify.ts index 1ba4331b524..3e10cbe49c2 100644 --- a/src/artifacts/inventory/classify.ts +++ b/src/artifacts/inventory/classify.ts @@ -10,6 +10,7 @@ import { releaseRootArtifact, abortIfNeeded, assertArtifactSelectedSource, + malformedArtifact, } from "../../resources/index.js"; import { nesContainerFormat } from "../../domain/inesContainer.js"; import { @@ -324,6 +325,21 @@ export const classifyEmbeddedExecutablePackage = async ( return { status: "absent" }; }; +/** + * Whether a PE's CLI header declares a Resources directory. A directory that + * cannot be located is refused with its reason, so extraction explains it. + */ +export const hasEmbeddedManagedResources = async ( + probes: ArtifactEmbeddedFormatProbes, +): Promise => { + const managed = await probes.managedImage(); + if (managed.state === "malformed") + throw malformedArtifact("dotnet-assembly", managed.reason, { + field: "cli-header", + }); + return managed.state === "located" && managed.location.resources !== null; +}; + const classifyRootFormat = async ( path: string, source: RootInventorySource, @@ -541,6 +557,15 @@ const classifyRootFormat = async ( (await locatesQualcommMbnHashSegment(read, archiveBytes)) ) return "qualcomm-mbn"; + // An assembly that embeds manifest resources lists them; a carried + // package or an unresolved recognition keeps its own classification. + if (format === "pe" && embeddedProbe.status === "absent") { + // A damaged CLI directory leaves the PE root; managed inspection, which + // leads its probes, reports the CLI header. + const managed = await embeddedProbes.managedImage(); + if (managed.state === "located" && managed.location.resources !== null) + return { kind: "dotnet-assembly", source, location: managed.location }; + } } if ( format === "asar" && diff --git a/src/artifacts/inventory/scanReader.ts b/src/artifacts/inventory/scanReader.ts index a0e1d7169c6..fe274a0b34b 100644 --- a/src/artifacts/inventory/scanReader.ts +++ b/src/artifacts/inventory/scanReader.ts @@ -327,7 +327,7 @@ const visitArtifactEntries = async ( ); const expandableAsar = isExpandableAsar(entry, logicalPath); // PyInstaller rows, Bun modules, Deno virtual files, and .NET resource - // names are source-distinct even when their logical destinations + // and manifest resource names are source-distinct even when their logical destinations // collide, as flat keys `a` and `a/b` do. // Inventory retains those observations; the extraction path registry // remains the authority for materialization. @@ -335,7 +335,8 @@ const visitArtifactEntries = async ( frame.reader.format !== "pyinstaller" && frame.reader.format !== "bun-standalone" && frame.reader.format !== "deno-standalone" && - frame.reader.format !== "dotnet-resources" + frame.reader.format !== "dotnet-resources" && + frame.reader.format !== "dotnet-assembly" ) context.registry.add( logicalPath, diff --git a/src/domain/artifactFormatMetadata.ts b/src/domain/artifactFormatMetadata.ts index 851943493cb..41b6c5f2793 100644 --- a/src/domain/artifactFormatMetadata.ts +++ b/src/domain/artifactFormatMetadata.ts @@ -1,5 +1,9 @@ import { z } from "zod"; import { arEntryMetadataSchema, arMetadataSchema } from "./arFormat.js"; +import { + dotnetAssemblyMetadataSchema, + dotnetAssemblyResourceMetadataSchema, +} from "./formatMetadata/dotnetAssemblyMetadata.js"; import { dotnetResourcesEntryMetadataSchema, dotnetResourcesMetadataSchema, @@ -129,6 +133,8 @@ export const artifactFormatMetadataSchema = z.discriminatedUnion("kind", [ arEntryMetadataSchema, dotnetResourcesMetadataSchema, dotnetResourcesEntryMetadataSchema, + dotnetAssemblyMetadataSchema, + dotnetAssemblyResourceMetadataSchema, switchExecutableMetadataSchema, switchExecutableEntryMetadataSchema, pyInstallerMetadataSchema, @@ -288,6 +294,10 @@ const declarationsByKind: { "type_code", "user_type_name", ), + "dotnet-assembly": + "The resource rows and directory come from the assembly's own bytes, which content comparison covers.", + /** What the manifest declares beyond the bytes: its visibility flags. The offset is layout. */ + "dotnet-assembly-resource": declaredFields("flags"), tar: "Its fields come from the archive's own bytes, which content comparison covers.", /** * What a header declares about a member beyond its bytes: its type, its diff --git a/src/domain/artifactGraph.ts b/src/domain/artifactGraph.ts index fa071d6ce34..8e8b99124eb 100644 --- a/src/domain/artifactGraph.ts +++ b/src/domain/artifactGraph.ts @@ -65,6 +65,7 @@ const artifactKindSchema = z.enum([ /** Recognized storage or application formats; unknown bytes remain explicit. */ export const ARTIFACT_FORMAT_IDS = [ "dotnet-bundle", + "dotnet-assembly", "bun-standalone", "deno-standalone", "dmg", diff --git a/src/domain/artifactInspection.ts b/src/domain/artifactInspection.ts index 4e92a2a31bb..35797045f9d 100644 --- a/src/domain/artifactInspection.ts +++ b/src/domain/artifactInspection.ts @@ -732,6 +732,17 @@ const probesForFormat = ( "Extract the stored virtual files into a fresh owned directory, then inspect compatible source separately. Environment-file values and CA certificate bytes remain in local Evidence with their counts and byte lengths, the npm snapshot stays undecoded, and the executable stays unrun.", }, ]; + // The assembly's metadata stays the lead; its resources follow. + if (format === "dotnet-assembly") + return [ + managedProbe("The PE declares a CLI header; read its managed metadata."), + { + operation: "extract_artifact", + rationale: + "Extract the embedded manifest resources into a fresh owned directory, then inspect each separately; a .resources member is a .NET resource set that inspect_artifact lists by resource name.", + authority: "artifact-bytes", + }, + ]; if (format === "dotnet-bundle") return [ { diff --git a/src/domain/artifactReaderLimits.test.ts b/src/domain/artifactReaderLimits.test.ts index aaed8268a3b..4b3b45eb092 100644 --- a/src/domain/artifactReaderLimits.test.ts +++ b/src/domain/artifactReaderLimits.test.ts @@ -92,3 +92,21 @@ it("resolves .NET resource counts from the shared setting and keeps historical E }).success, ).toBe(false); }); + +it("resolves .NET assembly resource counts from the shared setting and keeps historical Evidence", () => { + expect(resolveArtifactReaderLimits(undefined, 12).dotnet_assembly).toEqual({ + resource_count: 12, + metadata_bytes: 64 * 1024 * 1024, + representation_bytes: 64 * 1024 * 1024, + retained_name_bytes: 16 * 1024 * 1024, + }); + expect( + artifactMemberCountSelected( + { dotnet_assembly: { resource_count: 3 } }, + "artifact_limits.dotnet_assembly.resource_count", + ), + ).toBe(true); + const { dotnet_assembly: _omitted, ...recorded } = + resolveArtifactReaderLimits(); + expect(artifactReaderLimitsSchema.parse(recorded)).toEqual(recorded); +}); diff --git a/src/domain/artifactReaderLimits.ts b/src/domain/artifactReaderLimits.ts index 282736475d3..1f883ba8e6a 100644 --- a/src/domain/artifactReaderLimits.ts +++ b/src/domain/artifactReaderLimits.ts @@ -256,6 +256,22 @@ export const arReaderLimitsSchema = z.strictObject({ }); export type ArReaderLimits = z.output; +export const DEFAULT_DOTNET_ASSEMBLY_READER_LIMITS = { + resource_count: DEFAULT_ARTIFACT_MEMBER_COUNT, + metadata_bytes: 64 * 1024 * 1024, + representation_bytes: 64 * 1024 * 1024, + retained_name_bytes: 16 * 1024 * 1024, +}; +export const dotnetAssemblyReaderLimitsSchema = z.strictObject({ + resource_count: count, + metadata_bytes: representedBytes, + representation_bytes: representedBytes, + retained_name_bytes: bytes, +}); +export type DotnetAssemblyReaderLimits = z.output< + typeof dotnetAssemblyReaderLimitsSchema +>; + export const DEFAULT_DOTNET_RESOURCES_READER_LIMITS = { resource_count: DEFAULT_ARTIFACT_MEMBER_COUNT, type_count: 4096, @@ -504,6 +520,21 @@ export const artifactReaderLimitsInputSchema = z.strictObject({ .describe( `ar admission; omitted fields use ${JSON.stringify(DEFAULT_AR_READER_LIMITS)}. Header count includes name and symbol tables. Name bytes apply before decoding; retained bytes count source and logical names, including repeated references.`, ), + dotnet_assembly: z + .strictObject({ + resource_count: + dotnetAssemblyReaderLimitsSchema.shape.resource_count.exactOptional(), + metadata_bytes: + dotnetAssemblyReaderLimitsSchema.shape.metadata_bytes.exactOptional(), + representation_bytes: + dotnetAssemblyReaderLimitsSchema.shape.representation_bytes.exactOptional(), + retained_name_bytes: + dotnetAssemblyReaderLimitsSchema.shape.retained_name_bytes.exactOptional(), + }) + .exactOptional() + .describe( + `.NET assembly manifest resource admission; omitted fields use ${JSON.stringify(DEFAULT_DOTNET_ASSEMBLY_READER_LIMITS)}. Metadata bytes bound the CLI metadata read to list ManifestResource rows; representation bytes bound the decoded metadata rows and names; retained name bytes count every listed resource name, including names several rows share. Resource bytes are served from the file and not read into memory.`, + ), dotnet_resources: z .strictObject({ resource_count: @@ -564,6 +595,7 @@ const readerLimitGroups = { wxapkg: wxapkgReaderLimitsSchema, zip: zipReaderLimitsSchema, ar: arReaderLimitsSchema, + dotnet_assembly: dotnetAssemblyReaderLimitsSchema, dotnet_resources: dotnetResourcesReaderLimitsSchema, tar: tarReaderLimitsSchema, kubernetes_audit_log: kubernetesAuditLogReaderLimitsSchema, @@ -587,6 +619,7 @@ export const artifactReaderLimitsSchema = swf: swfReaderLimitsSchema.exactOptional(), android_dtbo: androidDtboReaderLimitsSchema.exactOptional(), ar: arReaderLimitsSchema.exactOptional(), + dotnet_assembly: dotnetAssemblyReaderLimitsSchema.exactOptional(), dotnet_resources: dotnetResourcesReaderLimitsSchema.exactOptional(), zip: zipReaderLimitsSchema.exactOptional(), kubernetes_audit_log: kubernetesAuditLogReaderLimitsSchema.exactOptional(), @@ -604,6 +637,7 @@ export const ARTIFACT_MEMBER_COUNT_PARAMETERS = [ "artifact_limits.zip.member_count", "artifact_limits.ar.header_count", "artifact_limits.dotnet_resources.resource_count", + "artifact_limits.dotnet_assembly.resource_count", ] as const satisfies readonly ArtifactReaderLimitParameter[]; export const resolveArtifactReaderLimits = ( @@ -664,6 +698,11 @@ export const resolveArtifactReaderLimits = ( header_count: memberCount, ...selected?.ar, }, + dotnet_assembly: { + ...DEFAULT_DOTNET_ASSEMBLY_READER_LIMITS, + resource_count: memberCount, + ...selected?.dotnet_assembly, + }, dotnet_resources: { ...DEFAULT_DOTNET_RESOURCES_READER_LIMITS, resource_count: memberCount, @@ -700,6 +739,8 @@ export const artifactMemberCountSelected = ( return selected?.ar?.header_count !== undefined; case "artifact_limits.dotnet_resources.resource_count": return selected?.dotnet_resources?.resource_count !== undefined; + case "artifact_limits.dotnet_assembly.resource_count": + return selected?.dotnet_assembly?.resource_count !== undefined; case "artifact_limits.zip.member_count": return selected?.zip?.member_count !== undefined; } diff --git a/src/domain/evidenceSubject.ts b/src/domain/evidenceSubject.ts index cd1deed10b1..05ca38e15d8 100644 --- a/src/domain/evidenceSubject.ts +++ b/src/domain/evidenceSubject.ts @@ -33,6 +33,7 @@ export const evidenceSubjectFormatSchema = z.enum([ "pyinstaller", "node-sea", "dotnet-bundle", + "dotnet-assembly", "bun-standalone", "deno-standalone", ...nonArtifactTargetFormats.slice(trailingArchiveIndex), diff --git a/src/domain/formatMetadata/dotnetAssemblyMetadata.ts b/src/domain/formatMetadata/dotnetAssemblyMetadata.ts new file mode 100644 index 00000000000..5bcf5a3f27a --- /dev/null +++ b/src/domain/formatMetadata/dotnetAssemblyMetadata.ts @@ -0,0 +1,44 @@ +import { z } from "zod"; + +const manifestResourceVisibility = z.enum(["public", "private", "unknown"]); + +export const dotnetAssemblyMetadataSchema = z.strictObject({ + kind: z.literal("dotnet-assembly"), + /** ManifestResource rows in the metadata. */ + resource_count: z.int().nonnegative(), + /** Rows whose data is embedded in this module's Resources directory. */ + embedded_count: z.int().nonnegative(), + /** Rows that name another file or assembly; their bytes are not here. */ + linked_resources: z.array( + z.strictObject({ + resource_name: z.string(), + token: z.string(), + implementation_token: z.string().nullable(), + }), + ), + /** File offset and size of the CLI Resources directory, when present. */ + resources_directory: z + .strictObject({ + offset: z.int().nonnegative(), + size: z.int().nonnegative(), + }) + .nullable(), +}); + +export const dotnetAssemblyResourceMetadataSchema = z.strictObject({ + kind: z.literal("dotnet-assembly-resource"), + resource_name: z.string(), + /** ManifestResource metadata token. */ + token: z.string(), + flags: z.int().nonnegative(), + visibility: manifestResourceVisibility, + /** Offset of the resource's length prefix within the Resources directory. */ + declared_offset: z.int().nonnegative(), +}); + +export type DotnetAssemblyMetadata = z.infer< + typeof dotnetAssemblyMetadataSchema +>; +export type DotnetAssemblyResourceMetadata = z.infer< + typeof dotnetAssemblyResourceMetadataSchema +>; diff --git a/src/domain/managed/managedCliHeaderPrefix.test.ts b/src/domain/managed/managedCliHeaderPrefix.test.ts index 34372b34ad3..c8a1cb63cd0 100644 --- a/src/domain/managed/managedCliHeaderPrefix.test.ts +++ b/src/domain/managed/managedCliHeaderPrefix.test.ts @@ -25,3 +25,21 @@ it("requires only the fixed prefix and leaves full-header admission to consumers }, ); }); + +it("reads the Resources directory when the prefix reaches it", () => { + const header = Buffer.alloc(32); + header.writeUInt32LE(72, 0); + header.writeUInt32LE(0x2050, 8); + header.writeUInt32LE(0x400, 12); + header.writeUInt32LE(0x3000, 24); + header.writeUInt32LE(0x120, 28); + expect(readManagedCliHeaderPrefix(header)).toMatchObject({ + ok: true, + value: { + metadata: { rva: 0x2050, size: 0x400 }, + resources: { rva: 0x3000, size: 0x120 }, + }, + }); + const short = readManagedCliHeaderPrefix(header.subarray(0, 16)); + expect(short.ok && "resources" in short.value).toBe(false); +}); diff --git a/src/domain/managed/managedCliHeaderPrefix.ts b/src/domain/managed/managedCliHeaderPrefix.ts index 05112e7ab5b..8fdd52a8282 100644 --- a/src/domain/managed/managedCliHeaderPrefix.ts +++ b/src/domain/managed/managedCliHeaderPrefix.ts @@ -1,7 +1,13 @@ import { BinaryReader } from "../binaryContainer.js"; import { err, ok } from "../result.js"; -/** IMAGE_COR20_HEADER's first 16 bytes; consumers own directory/range admission. */ +/** Bytes of IMAGE_COR20_HEADER through its Resources directory. */ +export const MANAGED_CLI_HEADER_RESOURCES_PREFIX_BYTES = 32; + +/** + * IMAGE_COR20_HEADER's first 16 bytes, and its Resources directory when the + * prefix reaches it; consumers own directory/range admission. + */ export const readManagedCliHeaderPrefix = (bytes: Buffer) => { if (bytes.length < 16) return err({ @@ -17,5 +23,8 @@ export const readManagedCliHeaderPrefix = (bytes: Buffer) => { rva: reader.u32(8), size: reader.u32(12), }, + ...(bytes.length < MANAGED_CLI_HEADER_RESOURCES_PREFIX_BYTES + ? {} + : { resources: { rva: reader.u32(24), size: reader.u32(28) } }), }); }; diff --git a/src/domain/managed/managedMetadataInventoryRows.ts b/src/domain/managed/managedMetadataInventoryRows.ts index 85431a31cee..1cbbf3c9d28 100644 --- a/src/domain/managed/managedMetadataInventoryRows.ts +++ b/src/domain/managed/managedMetadataInventoryRows.ts @@ -495,13 +495,26 @@ interface ReadResourceContext { readonly issues: ManagedParseIssue[]; } -export const readResource = ({ - bytes, - layout, - row, - directory, - issues, -}: ReadResourceContext): ManagedResource => { +/** One ManifestResource row's columns, without its data. */ +export interface ManifestResourceRow { + readonly token: string; + readonly rowOffset: number; + /** Offset of an embedded resource's length prefix in the Resources directory. */ + readonly declaredOffset: number; + readonly flags: number; + readonly name: string; + readonly visibility: "public" | "private" | "unknown"; + /** Null for a resource embedded in this module; invalid indexes add an issue. */ + readonly implementation: ReturnType; +} + +/** Read ManifestResource row `row`; an invalid implementation index adds an issue. */ +export const readManifestResourceRow = ( + bytes: Buffer, + layout: ManagedMetadataLayout, + row: number, + issues: ManagedParseIssue[], +): ManifestResourceRow => { const cursor = metadataRowCursor(bytes, layout, 40, row); const declaredOffset = cursor.u32(); const flags = cursor.u32(); @@ -523,6 +536,34 @@ export const readResource = ({ offset: implementationOffset, detail: `ManifestResource implementation coded index 0x${implementationRaw.toString(16)} is invalid: ${implementation.reason}`, }); + return { + token: metadataToken(40, row), + rowOffset: cursor.start, + declaredOffset, + flags, + name, + visibility: + (flags & 7) === 1 ? "public" : (flags & 7) === 2 ? "private" : "unknown", + implementation, + }; +}; + +export const readResource = ({ + bytes, + layout, + row, + directory, + issues, +}: ReadResourceContext): ManagedResource => { + const { + declaredOffset, + flags, + name, + visibility, + implementation, + token, + rowOffset, + } = readManifestResourceRow(bytes, layout, row, issues); let dataLength: number | null = null; let dataSha256: string | null = null; if (implementation.kind === "null") { @@ -554,15 +595,14 @@ export const readResource = ({ return { name, flags, - visibility: - (flags & 7) === 1 ? "public" : (flags & 7) === 2 ? "private" : "unknown", + visibility, implementation_token: implementation.kind === "valid" ? implementation.token : null, embedded: implementation.kind === "null", declared_offset: declaredOffset, data_length: dataLength, data_sha256: dataSha256, - token: metadataToken(40, row), - row_offset: cursor.start, + token, + row_offset: rowOffset, }; }; diff --git a/src/dotnet/ManagedPe.fixture.ts b/src/dotnet/ManagedPe.fixture.ts index 323ae005a7d..8c3d42b2ec2 100644 --- a/src/dotnet/ManagedPe.fixture.ts +++ b/src/dotnet/ManagedPe.fixture.ts @@ -72,6 +72,11 @@ interface ManagedPeFixtureOptions { readonly references?: readonly string[]; readonly resourceImplementationRaw?: number; readonly resourceData?: Buffer; + /** Embedded resources after `Fixture.resources`, in directory order. */ + readonly extraResources?: readonly { + readonly name: string; + readonly data: Buffer; + }[]; readonly targetFramework?: string | null; readonly typeName?: string; readonly typeNamespace?: string; @@ -413,14 +418,28 @@ const customAttributeRow = ({ metadataIndex(value, blobSize), ]); +const fixtureResourceData = (options: ManagedPeFixtureOptions): Buffer => + options.resourceData ?? Buffer.from("resource-data"); + +/** Directory offsets of the extra resources, after `Fixture.resources`. */ +const fixtureResourceOffsets = (options: ManagedPeFixtureOptions): number[] => { + let offset = 4 + fixtureResourceData(options).length; + return (options.extraResources ?? []).map(({ data }) => { + const at = offset; + offset += 4 + data.length; + return at; + }); +}; + const manifestResourceRow = ( name: number, stringSize: MetadataIndexSize, implementationSize: MetadataIndexSize, implementationRaw: number, + offset = 0, ): Buffer => Buffer.concat([ - u32(0), + u32(offset), u32(2), metadataIndex(name, stringSize), metadataIndex(implementationRaw, implementationSize), @@ -630,6 +649,7 @@ interface FixtureMetadataRowContext { readonly pinvokeModuleName: number | null; readonly pinvokeImportName: number | null; readonly resourceName: number; + readonly extraResourceNames: readonly number[]; readonly exportedTypes: readonly { readonly name: number; readonly namespace: number; @@ -1019,6 +1039,15 @@ const fixtureMetadataRows = ({ widths.implementation, options.resourceImplementationRaw ?? 0, ), + ...fixtureResourceOffsets(options).map((offset, index) => + manifestResourceRow( + indexes.extraResourceNames[index]!, + heapSizes.strings, + widths.implementation, + 0, + offset, + ), + ), ], ], ]); @@ -1099,6 +1128,9 @@ const buildManagedFixtureMetadata = ( ? null : strings.add(options.pinvoke.importName ?? "MessageBoxW"); const resourceName = strings.add("Fixture.resources"); + const extraResourceNames = (options.extraResources ?? []).map(({ name }) => + strings.add(name), + ); const exportedTypes = (options.exportedTypes ?? []).map( ({ namespace, name }) => ({ name: strings.add(name), @@ -1159,6 +1191,7 @@ const buildManagedFixtureMetadata = ( pinvokeModuleName, pinvokeImportName, resourceName, + extraResourceNames, exportedTypes, typeReferences, tokenBlob, @@ -1198,10 +1231,14 @@ const buildManagedFixtureImage = ( options: ManagedPeFixtureOptions, buildMetadata: (methodRva: number) => Buffer, ): Buffer => { - const resourceData = options.resourceData ?? Buffer.from("resource-data"); + const resourceData = fixtureResourceData(options); const resourceDirectory = Buffer.concat([ u32(resourceData.length), resourceData, + ...(options.extraResources ?? []).flatMap(({ data }) => [ + u32(data.length), + data, + ]), ]); const initialMetadata = buildMetadata(0); const resourceOffset = Math.max( diff --git a/src/resources/ArtifactReader.ts b/src/resources/ArtifactReader.ts index 6be5f31b1c8..95c4f52fa95 100644 --- a/src/resources/ArtifactReader.ts +++ b/src/resources/ArtifactReader.ts @@ -298,6 +298,7 @@ export interface ArtifactReader { | "uefi" | "pyinstaller" | "dotnet-bundle" + | "dotnet-assembly" | "bun-standalone" | "deno-standalone" | "node-sea" diff --git a/tests/acceptance/artifactReaderLimitsCli.test.ts b/tests/acceptance/artifactReaderLimitsCli.test.ts index 24a32821f42..63e60dd88c7 100644 --- a/tests/acceptance/artifactReaderLimitsCli.test.ts +++ b/tests/acceptance/artifactReaderLimitsCli.test.ts @@ -498,6 +498,7 @@ test("admits explicit member counts without reading an invalid artifact.member_c zip: { member_count: 2 }, ar: { header_count: 2 }, dotnet_resources: { resource_count: 2 }, + dotnet_assembly: { resource_count: 2 }, }), ], environment, diff --git a/tests/boundary/providers/native/artifactProvider.dotnetAssembly.test.ts b/tests/boundary/providers/native/artifactProvider.dotnetAssembly.test.ts new file mode 100644 index 00000000000..5077829e481 --- /dev/null +++ b/tests/boundary/providers/native/artifactProvider.dotnetAssembly.test.ts @@ -0,0 +1,178 @@ +import { readFile, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { expect, it } from "vitest"; +import { + dotnetResourcesFile, + resourceStream, + resourceString, +} from "../../../fixtures/dotnetResources.js"; +import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js"; +import { withArtifactClient } from "../../../support/artifactClientScope.js"; +import { parseBinaryTarget } from "../../../../src/application/BinaryTargetResolver.js"; +import { projectCliAnalysisResult } from "../../../../src/cli/projectCliAnalysisResult.js"; +import { createDirectAnalysis } from "../../../../src/composition/directAnalysis.js"; +import { artifactExtractionExecutionSchema } from "../../../../src/contracts/artifactToolContracts.js"; +import { buildManagedPeFixture } from "../../../../src/dotnet/ManagedPe.fixture.js"; +import { + artifactExtractionResultSchema, + artifactInventoryResultSchema, +} from "../../../../src/domain/artifactGraph.js"; +import { artifactInspectionResultSchema } from "../../../../src/domain/artifactInspection.js"; +import { parseEvidence } from "../../../../src/domain/evidence.js"; + +const { runProviderAnalysis } = createDirectAnalysis({}); + +const BAML = Buffer.concat([ + Buffer.of(0x0c, 0, 0, 0), + Buffer.from("MSBAML", "utf16le"), +]); + +const RESOURCE_SET = dotnetResourcesFile({ + "views/mainwindow.baml": resourceStream(BAML), + "strings/title": resourceString("Listary"), +}); + +const writeFixture = async (bytes: Buffer, name = "App.dll") => { + const directory = await createTestTempDirectory("rea-dotnet-assembly-"); + const path = join(directory, name); + await writeFile(path, bytes); + return { directory, path }; +}; + +const inspectArtifact = async (path: string) => { + const evidence = parseEvidence( + await runProviderAnalysis(path, "inspect_artifact", {}).then( + projectCliAnalysisResult, + ), + ); + const inspection = artifactInspectionResultSchema.parse( + evidence.normalized_result, + ); + const inventory = artifactInventoryResultSchema.parse( + inspection.substeps.find((step) => step.operation === "inventory_artifact") + ?.evidence.normalized_result, + ); + return { inspection, inventory }; +}; + +it("inventories embedded manifest resources and keeps the managed probes", async () => { + const { path } = await writeFixture( + buildManagedPeFixture({ resourceData: RESOURCE_SET }), + ); + const { inspection, inventory } = await inspectArtifact(path); + expect(inspection.subject.root_format).toBe("dotnet-assembly"); + expect(inventory.coverage.status).toBe("complete"); + expect( + inventory.occurrences.find( + ({ logical_path }) => logical_path === "Fixture.resources", + ), + ).toMatchObject({ + hash_status: "verified", + declared_size: RESOURCE_SET.length, + format_metadata: { kind: "dotnet-assembly-resource" }, + }); + const operations = inspection.next_probes.map(({ operation }) => operation); + expect(operations.slice(0, 2)).toEqual([ + "inspect_managed_artifact", + "extract_artifact", + ]); + expect(operations).toContain("inspect_pe_imports"); + expect(operations.at(-1)).toBe("open_binary"); +}); + +it("extracts an embedded resource set that then inventories as one", async () => { + const { directory, path } = await writeFixture( + buildManagedPeFixture({ resourceData: RESOURCE_SET }), + ); + const target = await parseBinaryTarget(path); + if (!target.ok) throw target.error; + const output = join(directory, "output"); + const result = await withArtifactClient(target.value, (client) => + client.execute( + "extract_artifact", + artifactExtractionExecutionSchema.parse({ output_root: output }), + ), + ); + if (!result.ok) throw result.error; + expect( + artifactExtractionResultSchema.parse(result.value.result), + ).toMatchObject({ output_root: output, containment_verified: true }); + const extracted = join(output, "Fixture.resources"); + expect((await readFile(extracted)).equals(RESOURCE_SET)).toBe(true); + + const nested = await inspectArtifact(extracted); + expect(nested.inspection.subject.root_format).toBe("dotnet-resources"); + expect( + nested.inventory.occurrences.map(({ logical_path }) => logical_path), + ).toEqual(expect.arrayContaining(["views/mainwindow.baml", "strings/title"])); +}); + +it("keeps a managed image without embedded resources a PE", async () => { + const bytes = buildManagedPeFixture(); + const cli = bytes.indexOf(Buffer.of(72, 0, 0, 0, 2, 0, 5, 0, 0, 0x21, 0, 0)); + bytes.writeUInt32LE(0, cli + 24); + bytes.writeUInt32LE(0, cli + 28); + const { path } = await writeFixture(bytes); + const { inspection } = await inspectArtifact(path); + expect(inspection.subject.root_format).toBe("pe"); + expect(inspection.next_probes[0]?.operation).toBe("inspect_managed_artifact"); +}); + +it("inventories flat names that collide as paths and extracts one at a time", async () => { + const { directory, path } = await writeFixture( + buildManagedPeFixture({ + resourceData: Buffer.from("fixture"), + extraResources: [ + { name: "a", data: Buffer.from("parent") }, + { name: "a/b", data: Buffer.from("child") }, + ], + }), + ); + const { inventory } = await inspectArtifact(path); + const child = inventory.occurrences.find( + ({ logical_path }) => logical_path === "a/b", + ); + expect( + inventory.occurrences.some(({ logical_path }) => logical_path === "a"), + ).toBe(true); + expect(child).toBeDefined(); + const target = await parseBinaryTarget(path); + if (!target.ok) throw target.error; + const output = join(directory, "output"); + const result = await withArtifactClient(target.value, (client) => + client.execute( + "extract_artifact", + artifactExtractionExecutionSchema.parse({ + output_root: output, + occurrence_ids: [child!.occurrence_id], + }), + ), + ); + if (!result.ok) throw result.error; + expect(await readFile(join(output, "a/b"), "utf8")).toBe("child"); +}); + +it("explains a Resources directory that cannot be located when extracting", async () => { + const bytes = buildManagedPeFixture(); + const cli = bytes.indexOf(Buffer.of(72, 0, 0, 0, 2, 0, 5, 0, 0, 0x21, 0, 0)); + bytes.writeUInt32LE(0x7fff_0000, cli + 24); + const { directory, path } = await writeFixture(bytes); + // Inspection keeps the PE root; managed inspection reports the CLI header. + expect((await inspectArtifact(path)).inspection.subject.root_format).toBe( + "pe", + ); + const target = await parseBinaryTarget(path); + if (!target.ok) throw target.error; + const result = await withArtifactClient(target.value, (client) => + client.execute( + "extract_artifact", + artifactExtractionExecutionSchema.parse({ + output_root: join(directory, "output"), + }), + ), + ); + expect(result.ok).toBe(false); + expect(result.ok ? undefined : result.error.message).toContain( + "The CLI Resources directory cannot be mapped", + ); +}); diff --git a/tests/boundary/providers/native/artifactProvider.nativeImageProbes.test.ts b/tests/boundary/providers/native/artifactProvider.nativeImageProbes.test.ts index e268fbcf6ae..e7f2c4e796c 100644 --- a/tests/boundary/providers/native/artifactProvider.nativeImageProbes.test.ts +++ b/tests/boundary/providers/native/artifactProvider.nativeImageProbes.test.ts @@ -134,7 +134,15 @@ it.each([ ); it("leads with managed inspection only when the PE declares a CLI header", async () => { - const inspected = await inspect("Fixture.dll", buildManagedPeFixture()); + // Without embedded resources the assembly stays a PE root; one that embeds + // them is a dotnet-assembly carrier, which its own test covers. + const managed = buildManagedPeFixture(); + const cli = managed.indexOf( + Buffer.of(72, 0, 0, 0, 2, 0, 5, 0, 0, 0x21, 0, 0), + ); + managed.writeUInt32LE(0, cli + 24); + managed.writeUInt32LE(0, cli + 28); + const inspected = await inspect("Fixture.dll", managed); expect(inspected.subject).toMatchObject({ architecture: "x86" }); expect(operations(inspected.probes)).toEqual([