diff --git a/.agents/skills/reverse-engineer-anything/SKILL.md b/.agents/skills/reverse-engineer-anything/SKILL.md index db669e36a38..47cf8bf923e 100644 --- a/.agents/skills/reverse-engineer-anything/SKILL.md +++ b/.agents/skills/reverse-engineer-anything/SKILL.md @@ -269,6 +269,9 @@ explicit path or endpoint and do not need it. [BEAM](https://github.com/morluto/rea/blob/main/docs/erlang-beam.md), [NuGet](https://github.com/morluto/rea/blob/main/docs/guides/managed/nuget-nupkg.md), [VSIX](https://github.com/morluto/rea/blob/main/docs/guides/managed/vsix-package.md)). + - YARA rules the caller supplies against one local file: + `inspect_yara_matches` with the file and `rule_paths`, run by the installed + `yara` command ([YARA guide](https://github.com/morluto/rea/blob/main/docs/guides/native/yara-matches.md)). - SQLite snapshot: `inspect_sqlite_database`; read the schema first and supply a quiescent snapshot rather than a live database/WAL pair ([SQLite guide](https://github.com/morluto/rea/blob/main/docs/guides/data/sqlite-databases.md)). 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 5c929fad56c..2f22ef5ed34 100644 --- a/.agents/skills/reverse-engineer-anything/references/native-and-artifacts.md +++ b/.agents/skills/reverse-engineer-anything/references/native-and-artifacts.md @@ -475,6 +475,23 @@ Child symbolic links are not followed. Directory form only; tar image layouts are not inspected. See [OCI image layouts](https://github.com/morluto/rea/blob/main/docs/guides/artifacts/oci-image-layout.md). +## YARA rule matches + +Use `inspect_yara_matches` when the caller supplies YARA rule files and asks +which rules match one explicit local file. It runs the installed `yara` command +(`REA_YARA_COMMAND` or `yara` on `PATH`) with an argument list, never a shell, +and needs no `open_binary`. REA ships no rules and downloads nothing; do not +write or fetch rules unless asked. The CLI equivalent is +`inspect-yara-matches PATH --rule_paths RULE`. Cite the file SHA-256 and each +rule file SHA-256 with the matched rules, tags, meta, and string offsets. +`data` is yara's display text; read `length` bytes at `file_offset` for exact +bytes. `coverage.status: "partial"` means string matches beyond `max_matches` +are counted but unlisted; raise `max_matches` to list them. A compile error is +`invalid_request` naming the rule file; fix the rule rather than retrying. A +missing command is `capability_unavailable`. Absent rules did not match; that +says nothing about why. See +[YARA rule matches](https://github.com/morluto/rea/blob/main/docs/guides/native/yara-matches.md). + ## SQLite snapshots Use `inspect_sqlite_database` with an explicit local database snapshot for its diff --git a/.cursor-plugin/skills/reverse-engineer-anything/SKILL.md b/.cursor-plugin/skills/reverse-engineer-anything/SKILL.md index db669e36a38..47cf8bf923e 100644 --- a/.cursor-plugin/skills/reverse-engineer-anything/SKILL.md +++ b/.cursor-plugin/skills/reverse-engineer-anything/SKILL.md @@ -269,6 +269,9 @@ explicit path or endpoint and do not need it. [BEAM](https://github.com/morluto/rea/blob/main/docs/erlang-beam.md), [NuGet](https://github.com/morluto/rea/blob/main/docs/guides/managed/nuget-nupkg.md), [VSIX](https://github.com/morluto/rea/blob/main/docs/guides/managed/vsix-package.md)). + - YARA rules the caller supplies against one local file: + `inspect_yara_matches` with the file and `rule_paths`, run by the installed + `yara` command ([YARA guide](https://github.com/morluto/rea/blob/main/docs/guides/native/yara-matches.md)). - SQLite snapshot: `inspect_sqlite_database`; read the schema first and supply a quiescent snapshot rather than a live database/WAL pair ([SQLite guide](https://github.com/morluto/rea/blob/main/docs/guides/data/sqlite-databases.md)). 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 5c929fad56c..2f22ef5ed34 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 @@ -475,6 +475,23 @@ Child symbolic links are not followed. Directory form only; tar image layouts are not inspected. See [OCI image layouts](https://github.com/morluto/rea/blob/main/docs/guides/artifacts/oci-image-layout.md). +## YARA rule matches + +Use `inspect_yara_matches` when the caller supplies YARA rule files and asks +which rules match one explicit local file. It runs the installed `yara` command +(`REA_YARA_COMMAND` or `yara` on `PATH`) with an argument list, never a shell, +and needs no `open_binary`. REA ships no rules and downloads nothing; do not +write or fetch rules unless asked. The CLI equivalent is +`inspect-yara-matches PATH --rule_paths RULE`. Cite the file SHA-256 and each +rule file SHA-256 with the matched rules, tags, meta, and string offsets. +`data` is yara's display text; read `length` bytes at `file_offset` for exact +bytes. `coverage.status: "partial"` means string matches beyond `max_matches` +are counted but unlisted; raise `max_matches` to list them. A compile error is +`invalid_request` naming the rule file; fix the rule rather than retrying. A +missing command is `capability_unavailable`. Absent rules did not match; that +says nothing about why. See +[YARA rule matches](https://github.com/morluto/rea/blob/main/docs/guides/native/yara-matches.md). + ## SQLite snapshots Use `inspect_sqlite_database` with an explicit local database snapshot for its diff --git a/docs/.vitepress/documentation.ts b/docs/.vitepress/documentation.ts index e21f91ac227..9868cd9751c 100644 --- a/docs/.vitepress/documentation.ts +++ b/docs/.vitepress/documentation.ts @@ -108,6 +108,11 @@ export const documentationSections = [ source: "guides/native/binary-diagnostics.md", route: "/binary-diagnostics", }, + { + text: "YARA rule matches", + source: "guides/native/yara-matches.md", + route: "/yara-matches", + }, { text: "ELF separate debug files", source: "guides/native/elf-debug-link.md", diff --git a/docs/README.md b/docs/README.md index 51e5d6f45d3..a9513fc9f3e 100644 --- a/docs/README.md +++ b/docs/README.md @@ -32,6 +32,7 @@ The [REA website](https://rea.tools/) has worked examples and product pages. - [Go binary build metadata](guides/native/go-binaries.md) - [DWARF compile units](guides/native/dwarf-units.md) - [Offline binary diagnostics](guides/native/binary-diagnostics.md) +- [YARA rule matches](guides/native/yara-matches.md) - [ELF separate debug files](guides/native/elf-debug-link.md) - [ELF and Mach-O initializer functions](guides/native/native-initializers.md) - [ELF unwind function ranges](guides/native/elf-unwind-ranges.md) diff --git a/docs/getting-started/cli.md b/docs/getting-started/cli.md index 5027f49d7a6..989e6a16879 100644 --- a/docs/getting-started/cli.md +++ b/docs/getting-started/cli.md @@ -828,6 +828,19 @@ digest mismatches, and similar defects are findings. Env values are kept unless `--no-include-env-values` is selected. Directory form only. See [OCI image layouts](../guides/artifacts/oci-image-layout.md). +Scan a local file with YARA rule files you supply, using the installed `yara` +command: + +```bash +rea inspect-yara-matches /absolute/path/to/sample.bin \ + --rule_paths /absolute/path/to/packers.yar --json +``` + +The workflow reports matching rules with tags, metadata and string match +offsets, bound to the SHA-256 of the file and of each rule file. Set +`REA_YARA_COMMAND` when `yara` is not on `PATH`. A rule that does not compile +is an input error naming its file. See [YARA rule matches](../guides/native/yara-matches.md). + Complete `rea decompile --json` Evidence can be saved and inspected through `inspect-analysis-view` with an inline source and `view: {kind: "native", facet: "pseudocode", offset: 0, limit: 20000}`. diff --git a/docs/guides/native/yara-matches.md b/docs/guides/native/yara-matches.md new file mode 100644 index 00000000000..b62456a0b60 --- /dev/null +++ b/docs/guides/native/yara-matches.md @@ -0,0 +1,155 @@ +# YARA rule matches + +`inspect_yara_matches` / `inspect-yara-matches` scans one selected local file +with YARA rule files that the caller supplies, using the `yara` command +installed on the host. It reports the matching rules with their tags, +metadata, and string match offsets, bound to the SHA-256 of the scanned file +and of each rule file. The file is read, never executed. REA ships no rules, +installs nothing, and downloads nothing. + +```bash +rea inspect-yara-matches /absolute/path/to/sample.bin \ + --rule_paths /absolute/path/to/packers.yar --json +``` + +Repeat `--rule_paths` to compile several rule files together, in the order +given. The CLI resolves relative paths against the caller's working directory. +MCP requires absolute paths and preserves the exact selection. There is no +artifact-id input: to scan a file pulled out of an archive or bundle, pass the +path of the extracted file. + +```json +{ + "name": "inspect_yara_matches", + "arguments": { + "path": "/artifacts/sample.bin", + "rule_paths": ["/rules/packers.yar", "/rules/crypto.yar"] + } +} +``` + +## Setup + +Install YARA 4.x from your package manager or the +[YARA releases](https://github.com/VirusTotal/yara/releases), then either put +`yara` on `PATH` or set `REA_YARA_COMMAND` to the executable. REA runs that +command and does not verify its implementation or version; the Evidence +records it as `yara.command` with no version. + +When the command cannot be found or started, the call fails with +`capability_unavailable` and the remediation names `REA_YARA_COMMAND`. Other +tools are unaffected. + +## How the scan runs + +REA streams each rule file and the scanned file into an owned private temporary +snapshot directory while computing each file's SHA-256 digest and verifying that +the source file did not change during acquisition. Relative `include "..."` +directives in staged rule files are resolved against each selected rule file's +directory so existing rule sets with relative includes continue to compile. It +then runs: + +```text +yara -s -L -m -g -q [-f] rea:... +``` + +The command is started directly with an argument list, never through a shell, +with its working directory at the root of the snapshot's filesystem. `-f` is +added when `fast_scan` is true. The child runs with `LC_ALL=C` and `LANG=C`. +Each rule argument carries a `rea:` namespace prefix so yara never splits a path +containing `:` into `NAMESPACE:FILE`. Match output names rules without the +namespace, and REA maps compile diagnostics and warnings back to the caller's +selected paths. Paths that contain a line break are refused, because yara's +output is line oriented. + +Because yara reads only the owned snapshot files bound to the computed SHA-256 +digests, concurrent renames or replacements of the caller's files or parent +directories after acquisition cannot attribute matches from different bytes to +the reported digests. Before reporting, REA verifies that none of the snapshot +files changed during the scan (failing with `artifact_changed` if one did) and +removes the snapshot directory. Cleanup that cannot be proven is retained and +retried before the next scan and on close. + +YARA output is parsed as it streams. Rule lines must name the scanned path, and +every string line must follow a rule line; anything else fails with a provider +output error instead of a partial result. + +## Observations + +`artifact` gives the scanned path, SHA-256, and byte length. `rule_files` gives +the same for each rule file, in the order passed to yara. + +Each entry in `matches` has: + +- `rule`: the rule identifier. +- `tags`: the rule's tags in declaration order. +- `meta`: each metadata entry with its `identifier`, `type` (`string`, + `integer`, `boolean`, or `bytes`), and `value`. A string value that is not + valid UTF-8 is reported as `bytes` with lowercase hex. An integer outside the + safe JSON range is reported as decimal text. +- `string_match_count`: every string match yara reported for the rule. +- `strings`: the listed string matches, each with `identifier`, `file_offset`, + `length`, and `data`. `data` is yara's display text: printable ASCII with + `\xNN` escapes for text and regex strings, and spaced hex for hex strings. + YARA may shorten long matches, so read `length` bytes at `file_offset` from + the artifact for the exact bytes. + +Rules that did not match are absent. `warnings` holds the warning lines yara +printed, such as slow-string warnings, verbatim, followed by any other stderr +line that matches none of yara's documented diagnostic forms. + +## Limits + +| Control | Setting | Launch seed | Default | Range | +| -------------------- | ------------------------- | ----------------------------- | -------- | ------------------ | +| `command_timeout_ms` | `yara.command_timeout_ms` | `REA_YARA_COMMAND_TIMEOUT_MS` | 60000 | 1 to 2147483647 | +| `max_output_bytes` | `yara.max_output_bytes` | `REA_YARA_MAX_OUTPUT_BYTES` | 67108864 | 4096 to 1073741824 | +| `max_matches` | `yara.max_matches` | `REA_YARA_MAX_MATCHES` | 256 | 1 to 100000 | +| `max_file_bytes` | none (per call only) | none | 2 GiB | 1 byte to 64 GiB | + +A call argument wins over a runtime override from `update_analysis_settings`, +which wins over the launch seed, which wins over the default. `limits` in the +result reports each value and its source. An invalid launch seed is refused +rather than replaced by the default. + +- `command_timeout_ms` bounds the yara process. When it elapses, REA stops the + process group and the call fails with a timeout that names the setting. +- `max_output_bytes` bounds the stdout REA parses and the stderr it keeps. + Output beyond it stops the scan with a resource error that names the + setting. +- `max_matches` bounds the string matches listed across all rules. Later + matches are still counted in `string_match_count` and `coverage`, so + `coverage.status` is `partial` and a limitation states how many are unlisted. + Raise `max_matches` to list them. +- `max_file_bytes` bounds the scanned file and each rule file. +- At most 64 rule files can be passed in one call. + +`fast_scan` passes `--fast-scan`, which stops at the first match of each +string; string match counts are then lower bounds. + +## Errors + +- A rule file that yara cannot compile fails with `invalid_request`. Each issue + names the rule file (`rule_paths[i]` when it is one of the selected files, or + `rule_paths` for an included file), the line, the rule when yara named one, + and yara's message. `diagnostics.compile_errors` records each error with a + `kind` read from yara 4.x's message text: `include` (an include file cannot + be opened, a circular include, or too many include levels), `syntax`, + `undefined` (an undefined identifier or string, or an unknown module), + `duplicate` (a duplicated rule, string, tag, or metadata identifier), + `unreadable_file`, or `other`. When a file name or message itself contains + `(N): ` and yara's text cannot be split into one file and line, `source` and + `line` are `null` and `message` keeps the whole text. The remediation gives + one repair per kind present. Rules that need external variables (`-d`) or module data cannot be + compiled by this tool. Stderr lines that match no documented form are kept + in `diagnostics.unrecognized_stderr_lines`. +- A missing or unreadable rule file is refused before yara starts. +- Cancellation stops the yara process group before the call returns. Cleanup + that cannot be proven is retained and retried before the next scan. + +## What the Evidence does not establish + +- Which yara implementation or version ran. +- The contents of files that a rule file `include`s, or module data yara read; + only the selected rule files are hashed. +- Why a rule did not match. diff --git a/docs/reference/rea-limit-inventory.md b/docs/reference/rea-limit-inventory.md index 4e4c1068771..e38d02ae85c 100644 --- a/docs/reference/rea-limit-inventory.md +++ b/docs/reference/rea-limit-inventory.md @@ -61,6 +61,9 @@ override is `source: "runtime"`. The structured field is `update_mode: "runtime" | `javascript.analysis_timeout_ms` | none (`analysis_timeout_ms`) | `src/domain/javascript/javascriptAnalysisResourceControls.ts` | 300000 | 1 | 2147483647 | per operation | | `javascript.max_heap_mb` | none (`max_heap_mb`) | `src/domain/javascript/javascriptAnalysisResourceControls.ts` | 1024 | 128 | 16384 | next worker | | `wasm.command_timeout_ms` | none (`command_timeout_ms`) | `src/domain/wasm/wasmArtifact.ts` | 30000 | 1 | 2147483647 | per operation | +| `yara.command_timeout_ms` | `REA_YARA_COMMAND_TIMEOUT_MS` | `src/domain/yara/yaraMatches.ts` | 60000 | 1 | 2147483647 | per operation | +| `yara.max_output_bytes` | `REA_YARA_MAX_OUTPUT_BYTES` | `src/domain/yara/yaraMatches.ts` | 67108864 | 4096 | 1073741824 | per operation | +| `yara.max_matches` | `REA_YARA_MAX_MATCHES` | `src/domain/yara/yaraMatches.ts` | 256 | 1 | 100000 | per operation | | `native.matching_representation_bytes` | `REA_NATIVE_MATCHING_REPRESENTATION_BYTES` | `src/domain/analysisResourceLimits.ts` | 100663296 | 1 | 1073741824 | per operation | | `delivery.agent_result_budget_bytes` | `REA_AGENT_RESULT_BUDGET_BYTES` | `src/domain/analysisResourceLimits.ts` | 32768 | 4096 | 10485760 | per operation | | `delivery.cli_retained_evidence_bytes` | `REA_CLI_RETAINED_EVIDENCE_BYTES` | `src/domain/analysisResourceLimits.ts` | 268435456 | 0 | 68719476736 | per CLI invocation | @@ -188,6 +191,7 @@ or logger. | `REA_WABT_BIN_DIRECTORY` | `src/wasm/WabtArtifactProvider.ts` | Filesystem root of the WABT tools. | | `REA_WAKARU_COMMAND` | `src/application/SetupRegistrationEnvironment.ts` | Caller-selected command. | | `REA_XPROP_COMMAND` | `src/application/desktop/DesktopCaptureFailure.ts` | Caller-selected command. | +| `REA_YARA_COMMAND` | `src/application/SetupRegistrationEnvironment.ts` | Caller-selected command. | `REA_MANAGED_LINUX_HOPPER_LAUNCHER` is a fixed path constant, and `REA_WORKFLOW_PROVIDER` is a provider identity object. Neither is an diff --git a/docs/reference/supported-targets.md b/docs/reference/supported-targets.md index dffe6bd0e03..00143a00ded 100644 --- a/docs/reference/supported-targets.md +++ b/docs/reference/supported-targets.md @@ -34,6 +34,7 @@ The table lists what REA returns for each target and which tools or host it requ | VS Code extensions | Identity from both manifests, activation, contributes, native/wasm members and ZIP inventory | Built-in static .vsix inspection; [VS Code extensions](../guides/managed/vsix-package.md) | | OCI image layouts | Layout version, index entries, image config, layers and blob digest verification | Built-in static directory inspection; [OCI image layouts](../guides/artifacts/oci-image-layout.md) | | WASM artifact | Validation, sections, exact import/export WAT forms and decoded WAT | Caller-supplied [WABT](../guides/wasm/wasm-artifacts.md#configure-wabt); `inspect_wasm_artifact` | +| YARA rule matches | Matching rules, tags, metadata and string offsets from caller-supplied rule files | Caller-supplied yara 4.x; [YARA rule matches](../guides/native/yara-matches.md) | | EVM bytecode | Dispatch selectors, byte offsets, inferred arguments and mutability | Local raw/hex carrier on Linux x64; [offline EVM guide](../guides/evm/evm-bytecode.md) | | SQLite databases | Tables, columns, indexes, views, triggers and selected ordinary-table rows | Local database/WAL snapshot; REA on Node.js 24.x or 26.x (unavailable on 22.x) | | Recorded Linux crashes | Raw notes, every recorded thread's registers/signals and optional mapping candidates | Caller-supplied pwntools on Linux x64; optional GDB/pwndbg; [recorded crashes](../guides/native/recorded-crashes.md) | diff --git a/scripts/lib/module-boundaries.mjs b/scripts/lib/module-boundaries.mjs index bcbb57642d2..2e24de1e942 100644 --- a/scripts/lib/module-boundaries.mjs +++ b/scripts/lib/module-boundaries.mjs @@ -20,6 +20,7 @@ const MIGRATED_PROVIDER_ROOTS = new Set([ "oci", "rust", "wasm", + "yara", "captures", "signals", "android", diff --git a/scripts/lib/module-layers.mjs b/scripts/lib/module-layers.mjs index 7a00318c7ef..b3e2d779212 100644 --- a/scripts/lib/module-layers.mjs +++ b/scripts/lib/module-layers.mjs @@ -93,6 +93,7 @@ export const UNIT_LAYERS = Object.freeze( "uefi", "v8", "wasm", + "yara", ]), ...units("application", ["application"]), ...units("composition", ["composition"]), @@ -409,6 +410,7 @@ export const ENTRY_FILES = Object.freeze( sqlite: ["SqliteDatabaseProvider.ts"], v8: ["V8CodeCacheProvider.ts", "V8CodeCacheProviderIdentity.ts"], wasm: ["WabtArtifactProvider.ts", "WabtRelease.ts"], + yara: ["YaraMatchesProvider.ts", "YaraProviderIdentity.ts"], }).map(([unit, files]) => [unit, Object.freeze(files)]), ), ); diff --git a/scripts/lib/test-projects.mjs b/scripts/lib/test-projects.mjs index dabb09088b7..6f68710bdce 100644 --- a/scripts/lib/test-projects.mjs +++ b/scripts/lib/test-projects.mjs @@ -19,7 +19,7 @@ export const SOURCE_TEST_PROJECTS = [ group: "source", include: [ "src/*.test.ts", - "src/{android,apkSignature,apktool,jeb,adb,artifacts,browser,compression,config,cutter,deb,desktop,dotnet,electron,erlang,evm,firmware,flutter,frida,pcap,ghidra,go,gpu,hopper,hopperPaths,ida,inspector,java,javascript,kuna,main,native,nuget,oci,process,providers,python,reference,resources,rust,server,sqlite,uefi,v8,vsix,wasm,windows}/**/*.test.ts", + "src/{android,apkSignature,apktool,jeb,adb,artifacts,browser,compression,config,cutter,deb,desktop,dotnet,electron,erlang,evm,firmware,flutter,frida,pcap,ghidra,go,gpu,hopper,hopperPaths,ida,inspector,java,javascript,kuna,main,native,nuget,oci,process,providers,python,reference,resources,rust,server,sqlite,uefi,v8,vsix,wasm,windows,yara}/**/*.test.ts", ], }, { diff --git a/scripts/verify/advertised-schemas/tools/inspect_analysis_settings.json b/scripts/verify/advertised-schemas/tools/inspect_analysis_settings.json index cfc3e95ab98..5d3a7de75d6 100644 --- a/scripts/verify/advertised-schemas/tools/inspect_analysis_settings.json +++ b/scripts/verify/advertised-schemas/tools/inspect_analysis_settings.json @@ -1,6 +1,6 @@ { "schemas": { - "input compact": "bf69936321d1b7c7", + "input compact": "0f8207f2279093da", "output compact": "b3a429110120aff1" }, "patterns": {} diff --git a/scripts/verify/advertised-schemas/tools/inspect_yara_matches.json b/scripts/verify/advertised-schemas/tools/inspect_yara_matches.json new file mode 100644 index 00000000000..860bdfe7d98 --- /dev/null +++ b/scripts/verify/advertised-schemas/tools/inspect_yara_matches.json @@ -0,0 +1,9 @@ +{ + "schemas": { + "input compact": "e8a9e0c4cd423964", + "output compact": "fc6c5d5a78a47254" + }, + "patterns": { + "input": ["^[^\\x00]*$"] + } +} diff --git a/scripts/verify/advertised-schemas/tools/update_analysis_settings.json b/scripts/verify/advertised-schemas/tools/update_analysis_settings.json index a0bbe0ada29..36f6af7186b 100644 --- a/scripts/verify/advertised-schemas/tools/update_analysis_settings.json +++ b/scripts/verify/advertised-schemas/tools/update_analysis_settings.json @@ -1,6 +1,6 @@ { "schemas": { - "input compact": "7fa9c27aaf84456c", + "input compact": "9d4e260b7995138e", "output compact": "39446aa1012006cc" }, "patterns": {} diff --git a/src/application/SetupRegistrationEnvironment.ts b/src/application/SetupRegistrationEnvironment.ts index 7183c604d8f..1ba217dd6f0 100644 --- a/src/application/SetupRegistrationEnvironment.ts +++ b/src/application/SetupRegistrationEnvironment.ts @@ -15,6 +15,7 @@ const SELECTED_REGISTRATION_SETTINGS = [ "REA_CAPINFOS_COMMAND", "REA_TSHARK_PRLIMIT_COMMAND", "REA_OBJDUMP_COMMAND", + "REA_YARA_COMMAND", "REA_GDB_COMMAND", "REA_RIZIN_COMMAND", "REA_CUTTER_BRIDGE_DIR", diff --git a/src/application/yara/YaraMatchesService.test.ts b/src/application/yara/YaraMatchesService.test.ts new file mode 100644 index 00000000000..fda799bf0b2 --- /dev/null +++ b/src/application/yara/YaraMatchesService.test.ts @@ -0,0 +1,107 @@ +import { expect, it, vi } from "vitest"; + +import { ok } from "../../domain/result.js"; +import type { YaraMatches } from "../../domain/yara/yaraMatches.js"; +import type { YaraMatchesPort } from "../../ports/yara/YaraMatchesPort.js"; +import { YaraMatchesService } from "./YaraMatchesService.js"; + +const SHA = "a".repeat(64); + +const report = (path: string): YaraMatches => ({ + artifact: { path, sha256: SHA, bytes: 4 }, + rule_files: [{ path: "/rules/a.yar", sha256: SHA, bytes: 10 }], + fast_scan: false, + matches: [ + { + rule: "A", + tags: [], + meta: [], + string_match_count: 1, + strings: [{ identifier: "$a", file_offset: 0, length: 1, data: "A" }], + }, + ], + coverage: { + status: "complete", + matched_rules: 1, + string_matches: 1, + listed_string_matches: 1, + }, + limits: { + max_matches: { value: 256, source: "default" }, + max_output_bytes: { value: 64 * 1024 * 1024, source: "default" }, + command_timeout_ms: { value: 60_000, source: "default" }, + max_file_bytes: 2 * 1024 * 1024 * 1024, + }, + warnings: [], + limitations: ["observed"], +}); + +const provider = (value: YaraMatches) => { + const inspect = vi.fn(async () => ok(value)); + const port: YaraMatchesPort = { + identity: { id: "yara.command", name: "yara command", version: null }, + close: async () => {}, + inspect, + }; + return { port, inspect }; +}; + +const INPUT = { path: "/work/sample.bin", rule_paths: ["/rules/a.yar"] }; + +it("records only the caller's selections as Evidence parameters", async () => { + const observed = report(INPUT.path); + const { port, inspect } = provider({ + ...observed, + limits: { + ...observed.limits, + max_matches: { value: 256, source: "runtime" }, + }, + }); + const service = new YaraMatchesService(port, {}, () => ({ + revision: 1, + overrides: { "yara.max_matches": 256 }, + })); + const result = await service.inspect(INPUT); + expect(result.ok).toBe(true); + if (!result.ok) return; + expect(result.value.parameters).toEqual(INPUT); + expect(inspect.mock.calls[0]?.[0].settings.max_matches).toEqual({ + value: 256, + source: "runtime", + }); +}); + +it("refuses a report whose path or limits differ from the request", async () => { + const moved = new YaraMatchesService( + provider(report("/work/other.bin")).port, + {}, + ); + const result = await moved.inspect(INPUT); + expect(!result.ok && result.error._tag).toBe("AnalysisOutputError"); + const seeded = new YaraMatchesService(provider(report(INPUT.path)).port, { + REA_YARA_MAX_MATCHES: "5", + }); + const limited = await seeded.inspect(INPUT); + expect(!limited.ok && limited.error._tag).toBe("AnalysisOutputError"); +}); + +it("refuses an invalid launch seed before calling the provider", async () => { + const { port, inspect } = provider(report(INPUT.path)); + const service = new YaraMatchesService(port, { + REA_YARA_COMMAND_TIMEOUT_MS: "soon", + }); + const result = await service.inspect(INPUT); + expect(!result.ok && result.error._tag).toBe("ConfigurationError"); + expect(inspect).not.toHaveBeenCalled(); +}); + +it("returns cancellation without calling the provider", async () => { + const { port, inspect } = provider(report(INPUT.path)); + const controller = new AbortController(); + controller.abort(); + const result = await new YaraMatchesService(port, {}).inspect(INPUT, { + signal: controller.signal, + }); + expect(!result.ok && result.error._tag).toBe("AnalysisCancelledError"); + expect(inspect).not.toHaveBeenCalled(); +}); diff --git a/src/application/yara/YaraMatchesService.ts b/src/application/yara/YaraMatchesService.ts new file mode 100644 index 00000000000..7fbc028ee62 --- /dev/null +++ b/src/application/yara/YaraMatchesService.ts @@ -0,0 +1,136 @@ +import { resolveYaraScanSettings } from "../../config/yaraScanLimits.js"; +import type { AnalysisError } from "../../domain/analysisErrorBase.js"; +import { AnalysisOutputError } from "../../domain/analysisErrorCore.js"; +import type { AnalysisSettingsReader } from "../../domain/analysisSettings.js"; +import type { Evidence } from "../../domain/evidence.js"; +import { err, type Result } from "../../domain/result.js"; +import { + INSPECT_YARA_MATCHES_OPERATION, + inspectYaraMatchesInputSchema, + YARA_FILE_BYTES, + yaraMatchesSchema, + type InspectYaraMatchesInput, + type YaraMatches, + type YaraScanSettings, +} from "../../domain/yara/yaraMatches.js"; +import type { ExecutionOptions } from "../../ports/AnalysisProvider.js"; +import type { YaraMatchesPort } from "../../ports/yara/YaraMatchesPort.js"; +import { + callerAnalysisParameters, + parseAnalysisInput, +} from "../AnalysisInput.js"; +import { observedFileEvidence } from "../observedFileEvidence.js"; +import { + completeProviderEvidence, + retainCompletedArtifactEvidence, +} from "../ProviderOperationExecution.js"; + +const OPERATION = INSPECT_YARA_MATCHES_OPERATION; + +/** Shared caller validation, limit resolution and Evidence provenance for CLI/MCP. */ +export class YaraMatchesService { + constructor( + readonly provider: YaraMatchesPort, + readonly environment: Readonly>, + readonly settings?: AnalysisSettingsReader, + ) {} + + close(): Promise { + return this.provider.close(); + } + + async inspect( + rawInput: unknown, + options?: ExecutionOptions, + ): Promise> { + const input = parseAnalysisInput( + OPERATION, + rawInput, + inspectYaraMatchesInputSchema, + options?.signal, + ); + if (!input.ok) return input; + const settings = resolveYaraScanSettings( + input.value, + this.environment, + this.settings, + ); + if (!settings.ok) return settings; + const parameters = callerAnalysisParameters(rawInput)(input.value); + const buildEvidence = (report: YaraMatches): Evidence => + observedFileEvidence( + report, + this.provider.identity, + OPERATION, + parameters, + report.rule_files.map(({ path }) => ({ + kind: "artifact-path" as const, + path, + })), + ); + const inspected = await this.provider.inspect( + { input: input.value, settings: settings.value }, + options, + ); + if (!inspected.ok) { + const partial = yaraMatchesSchema.safeParse( + inspected.error.partialObservation, + ); + if ( + partial.success && + validReport(partial.data, input.value, settings.value) + ) + retainCompletedArtifactEvidence( + inspected.error, + buildEvidence(partial.data), + ); + return inspected; + } + const report = yaraMatchesSchema.safeParse(inspected.value); + if ( + !report.success || + !validReport(report.data, input.value, settings.value) + ) + return err( + new AnalysisOutputError( + OPERATION, + "yara provider returned malformed output or changed the selected file identity.", + ), + ); + return completeProviderEvidence( + buildEvidence(report.data), + options?.signal, + ); + } +} + +const validReport = ( + report: YaraMatches, + input: InspectYaraMatchesInput, + settings: YaraScanSettings, +): boolean => { + const listed = report.matches.reduce( + (total, match) => total + match.strings.length, + 0, + ); + const counted = report.matches.reduce( + (total, match) => total + match.string_match_count, + 0, + ); + return ( + report.artifact.path === input.path && + JSON.stringify(report.rule_files.map(({ path }) => path)) === + JSON.stringify(input.rule_paths) && + report.fast_scan === (input.fast_scan === true) && + JSON.stringify(report.limits) === + JSON.stringify({ + ...settings, + max_file_bytes: input.max_file_bytes ?? YARA_FILE_BYTES.default_value, + }) && + report.coverage.matched_rules === report.matches.length && + report.coverage.listed_string_matches === listed && + report.coverage.string_matches === counted && + listed <= settings.max_matches.value && + report.coverage.status === (listed < counted ? "partial" : "complete") + ); +}; diff --git a/src/cli.ts b/src/cli.ts index 97e39f6ab25..e42ab0b5216 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -36,6 +36,7 @@ import * as debPackageModule from "./cli/debPackageCommands.js"; import * as nugetNupkgModule from "./cli/nugetNupkgCommands.js"; import * as vsixPackageModule from "./cli/vsixPackageCommands.js"; import * as ociImageLayoutModule from "./cli/ociImageLayoutCommands.js"; +import * as yaraModule from "./cli/yaraCommands.js"; import * as erlangModule from "./cli/erlangCommands.js"; import * as v8CodeCacheModule from "./cli/v8CodeCacheCommands.js"; import * as mavenGradleMetadataModule from "./cli/mavenGradleMetadataCommands.js"; @@ -101,6 +102,7 @@ const CLI_COMMAND_MODULES: CliCommandModules = { nugetNupkg: nugetNupkgModule, vsixPackage: vsixPackageModule, ociImageLayout: ociImageLayoutModule, + yara: yaraModule, erlang: erlangModule, v8CodeCache: v8CodeCacheModule, mavenGradleMetadata: mavenGradleMetadataModule, diff --git a/src/cli/cliCommandRegistrations.ts b/src/cli/cliCommandRegistrations.ts index aa5fabe84ce..945818c298a 100644 --- a/src/cli/cliCommandRegistrations.ts +++ b/src/cli/cliCommandRegistrations.ts @@ -116,6 +116,10 @@ export const CLI_COMMAND_REGISTRATIONS = { () => import("./ociImageLayoutCommands.js"), "registerOciImageLayoutCommands", ), + yara: cliRegistrarWithEnvironment( + () => import("./yaraCommands.js"), + "registerYaraCommands", + ), erlang: cliRegistrar( () => import("./erlangCommands.js"), "registerErlangCommands", @@ -320,6 +324,7 @@ const CLI_FAMILY_REGISTRATIONS: { "nugetNupkg", "vsixPackage", "ociImageLayout", + "yara", "erlang", "v8CodeCache", "mavenGradleMetadata", diff --git a/src/cli/contractCliDescription.ts b/src/cli/contractCliDescription.ts index e1786054388..0253ef7ec4b 100644 --- a/src/cli/contractCliDescription.ts +++ b/src/cli/contractCliDescription.ts @@ -268,9 +268,13 @@ export const describeContractCommand = < : analysisEvidenceDeliveryOptions.detail; else if (jsonText) schema = jsonTextField(declared, optionFlagName(key)); else if (callerPath) { + const unwrapped = core(declared); const admitted = - core(declared) instanceof z.ZodArray - ? z.array(localPathStringSchema) + unwrapped instanceof z.ZodArray + ? new z.ZodArray({ + ...unwrapped._zod.def, + element: localPathStringSchema, + }) : localPathStringSchema; schema = admitsOmission(declared) ? admitted.optional() : admitted; } else { diff --git a/src/cli/yaraCommands.ts b/src/cli/yaraCommands.ts new file mode 100644 index 00000000000..771582c68ac --- /dev/null +++ b/src/cli/yaraCommands.ts @@ -0,0 +1,38 @@ +import type { Logger } from "pino"; + +import { createYaraMatchesService } from "../composition/yara.js"; +import { YARA_TOOL_CONTRACTS } from "../contracts/yara/yaraToolContracts.js"; +import { contractNamed } from "./contractCliDescription.js"; +import { registerContractCommand } from "./contractCommand.js"; +import { inspectWithService } from "./contractCommandRunners.js"; +import type { CliInstance } from "./types.js"; + +/** Scan an operator-selected file with operator-selected rules, as over MCP. */ +export const registerYaraCommands = ( + cli: CliInstance, + logger: Logger, + environment: Readonly, +): void => { + registerContractCommand( + cli, + logger, + contractNamed(YARA_TOOL_CONTRACTS, "inspect_yara_matches"), + { + description: + "Scan a local file with caller-supplied YARA rule files using the installed yara command", + positionals: ["path"], + callerPaths: ["path", "rule_paths"], + fields: { + path: { description: "Local file to scan" }, + rule_paths: { + name: "rule_paths", + description: "Local YARA rule source files", + }, + }, + }, + inspectWithService( + () => createYaraMatchesService(environment), + "rea-yara-matches", + ), + ); +}; diff --git a/src/composition/capabilityDeclarations.ts b/src/composition/capabilityDeclarations.ts index a67402964e6..07d27878536 100644 --- a/src/composition/capabilityDeclarations.ts +++ b/src/composition/capabilityDeclarations.ts @@ -104,6 +104,7 @@ import { PCAP_PROVIDER_IDENTITY } from "../pcap/PcapProviderIdentity.js"; import { NUGET_NUPKG_PROVIDER_IDENTITY } from "../nuget/NugetNupkgProviderIdentity.js"; import { VSIX_PACKAGE_PROVIDER_IDENTITY } from "../vsix/VsixPackageProviderIdentity.js"; import { OCI_IMAGE_LAYOUT_PROVIDER_IDENTITY } from "../oci/OciImageLayoutProviderIdentity.js"; +import { YARA_PROVIDER_IDENTITY } from "../yara/YaraProviderIdentity.js"; import { PYTHON_PYC_PROVIDER_IDENTITY } from "../python/PythonPycProviderIdentity.js"; import { DEB_PACKAGE_PROVIDER_IDENTITY } from "../deb/DebPackageProviderIdentity.js"; import { RIZIN_DEBUGGER_PROVIDER_IDENTITY } from "../rizin/RizinDebuggerProviderIdentity.js"; @@ -547,6 +548,13 @@ export const CAPABILITY_DECLARATIONS = { }), ], }, + yaraMatches: { + providers: [ + providerBinding(YARA_PROVIDER_IDENTITY, { + group: "YARA_TOOL_CONTRACTS", + }), + ], + }, releaseExposure: { providers: [ providerBinding(RELEASE_EXPOSURE_PROVIDER, { diff --git a/src/composition/capabilityServices.ts b/src/composition/capabilityServices.ts index 2f9b97d2c5c..aa3e1a009de 100644 --- a/src/composition/capabilityServices.ts +++ b/src/composition/capabilityServices.ts @@ -52,6 +52,7 @@ import { createDebPackageService } from "./debPackage.js"; import { createNugetNupkgService } from "./nugetNupkg.js"; import { createVsixPackageService } from "./vsixPackage.js"; import { createOciImageLayoutService } from "./ociImageLayout.js"; +import { createYaraMatchesService } from "./yara.js"; import { createWebNetworkCaptureService } from "./webNetworkCaptures.js"; import { createWebSourceLocationService } from "./webSourceLocations.js"; import { createWebModuleTraceService } from "./webModules.js"; @@ -119,6 +120,7 @@ import type { DebPackageService } from "../application/deb/DebPackageService.js" import type { NugetNupkgService } from "../application/nuget/NugetNupkgService.js"; import type { VsixPackageService } from "../application/vsix/VsixPackageService.js"; import type { OciImageLayoutService } from "../application/oci/OciImageLayoutService.js"; +import type { YaraMatchesService } from "../application/yara/YaraMatchesService.js"; import type { BeamService } from "../application/erlang/BeamService.js"; import type { V8CodeCacheService } from "../application/v8CodeCache/V8CodeCacheService.js"; import type { MavenGradleMetadataService } from "../application/java/MavenGradleMetadataService.js"; @@ -159,6 +161,7 @@ export interface CapabilityServiceOptions { readonly nugetNupkg?: NugetNupkgService; readonly vsixPackage?: VsixPackageService; readonly ociImageLayout?: OciImageLayoutService; + readonly yaraMatches?: YaraMatchesService; readonly erlangBeam?: BeamService; readonly v8CodeCache?: V8CodeCacheService; readonly mavenGradleMetadata?: MavenGradleMetadataService; @@ -444,6 +447,11 @@ const modules = { ociImageLayout: service( ({ options }) => options.ociImageLayout ?? createOciImageLayoutService(), ), + yaraMatches: service( + ({ environment, options, platform, settings }) => + options.yaraMatches ?? + createYaraMatchesService(environment, settings, platform), + ), webNetworkCapture: service( ({ environment, options, settings }) => options.webNetworkCapture ?? diff --git a/src/composition/yara.ts b/src/composition/yara.ts new file mode 100644 index 00000000000..62c29eb1fff --- /dev/null +++ b/src/composition/yara.ts @@ -0,0 +1,81 @@ +import { posix } from "node:path"; + +import { YaraMatchesService } from "../application/yara/YaraMatchesService.js"; +import { AnalysisCapabilityUnavailableError } from "../domain/analysisErrorCore.js"; +import type { AnalysisSettingsReader } from "../domain/analysisSettings.js"; +import { err, ok } from "../domain/result.js"; +import { INSPECT_YARA_MATCHES_OPERATION } from "../domain/yara/yaraMatches.js"; +import { absoluteCallerPath } from "../filesystem/callerPath.js"; +import { HOST_PLATFORM } from "../platform/HostPlatform.js"; +import { + YARA_COMMAND_REMEDIATION, + YARA_COMMAND_SETTING, + YARA_PROVIDER_IDENTITY, +} from "../yara/YaraProviderIdentity.js"; +import { + YaraMatchesProvider, + type YaraCommandSelection, +} from "../yara/YaraMatchesProvider.js"; +import { resolveWindowsProviderExecutable } from "./resolveWindowsProviderExecutable.js"; + +/** + * Bind the configured yara executable. Relative paths are resolved against the + * caller's working directory before the provider switches the child to the + * filesystem root; Windows bare names are resolved on PATH. + */ +const selectYaraCommand = + ( + environment: Readonly, + platform: NodeJS.Platform, + ): YaraCommandSelection => + () => { + const command = environment[YARA_COMMAND_SETTING] ?? "yara"; + if (command.trim() === "") + return err( + new AnalysisCapabilityUnavailableError( + YARA_PROVIDER_IDENTITY.id, + INSPECT_YARA_MATCHES_OPERATION, + `${YARA_COMMAND_SETTING} is set but empty.`, + { remediationAction: YARA_COMMAND_REMEDIATION }, + ), + ); + if (platform !== "win32") + return ok( + command.includes("/") && !posix.isAbsolute(command) + ? absoluteCallerPath(command, { platform }) + : command, + ); + const resolved = resolveWindowsProviderExecutable(command, environment); + if (resolved.ok) return resolved; + return err( + new AnalysisCapabilityUnavailableError( + YARA_PROVIDER_IDENTITY.id, + INSPECT_YARA_MATCHES_OPERATION, + resolved.error.kind === "not_found" + ? `The yara command ${command} was not found on PATH.` + : `PATHEXT contains an invalid extension (${resolved.error.extension}).`, + { remediationAction: YARA_COMMAND_REMEDIATION }, + ), + ); + }; + +/** + * Compose caller-supplied YARA scanning. Construction performs no lookup, + * acquisition or target I/O; the command is selected when a scan starts. + */ +export const createYaraMatchesService = ( + environment: Readonly = process.env, + settings?: AnalysisSettingsReader, + platform: NodeJS.Platform = HOST_PLATFORM.platform, +): YaraMatchesService => { + const snapshot = { ...environment }; + return new YaraMatchesService( + new YaraMatchesProvider({ + environment: snapshot, + platform, + selectCommand: selectYaraCommand(snapshot, platform), + }), + snapshot, + settings, + ); +}; diff --git a/src/config/analysisSettings.ts b/src/config/analysisSettings.ts index 8179a75ffb0..d5c32fe6085 100644 --- a/src/config/analysisSettings.ts +++ b/src/config/analysisSettings.ts @@ -35,6 +35,7 @@ import { windowsChangeTimeSettlePollMsSchema, } from "./windowsChangeTimeSettle.js"; import { pwntoolsInputBytesSchema } from "./pwntoolsInputLimit.js"; +import { YARA_SETTING_SEEDS } from "./yaraSettingSeeds.js"; import { producerOutputBytesSchema } from "./producerOutputBytesSeed.js"; import { zstandardMaxFramesSchema } from "../domain/compression/zstandardFrameAllowance.js"; import { @@ -77,6 +78,7 @@ const environmentSchemas: Readonly>> = REA_WINDOWS_CHANGE_TIME_SETTLE_MAX_POLLS: windowsChangeTimeSettleMaxPollsSchema, REA_ZSTD_MAX_FRAMES: zstandardMaxFramesSchema, + ...YARA_SETTING_SEEDS, REA_AGENT_RESULT_BUDGET_BYTES: agentResultBudgetBytesSchema, REA_CLI_RETAINED_EVIDENCE_BYTES: cliRetainedEvidenceBytesSchema, }; diff --git a/src/config/yaraScanLimits.ts b/src/config/yaraScanLimits.ts new file mode 100644 index 00000000000..98e17810909 --- /dev/null +++ b/src/config/yaraScanLimits.ts @@ -0,0 +1,50 @@ +import { launchAnalysisSetting } from "./analysisSettings.js"; +import type { AnalysisSettingsReader } from "../domain/analysisSettings.js"; +import type { ConfigurationError } from "../domain/configurationErrors.js"; +import { err, ok, type Result } from "../domain/result.js"; +import type { + YaraScanSettings, + YaraSettingValue, +} from "../domain/yara/yaraMatches.js"; + +const SETTINGS = { + max_matches: "yara.max_matches", + max_output_bytes: "yara.max_output_bytes", + command_timeout_ms: "yara.command_timeout_ms", +} as const satisfies Record; + +/** + * Resolve each control: the caller's argument, then the accepted runtime + * override, then the launch seed, then the default. An invalid seed is + * refused rather than replaced by the default. + */ +export const resolveYaraScanSettings = ( + request: Partial>, + environment: Readonly>, + settings: AnalysisSettingsReader | undefined, +): Result => { + const overrides = settings?.().overrides; + const resolved: Partial> = + {}; + for (const parameter of Object.keys(SETTINGS) as (keyof YaraScanSettings)[]) { + const setting = SETTINGS[parameter]; + const requested = request[parameter]; + const override = overrides?.[setting]; + if (requested !== undefined) { + resolved[parameter] = { value: requested, source: "request" }; + continue; + } + if (override !== undefined) { + resolved[parameter] = { value: override, source: "runtime" }; + continue; + } + const launch = launchAnalysisSetting(setting, environment); + if (!launch.ok) return err(launch.error); + // Every yara setting has a numeric default, so the launch value is a number. + resolved[parameter] = { + value: launch.value.value as number, + source: launch.value.source, + }; + } + return ok(resolved as YaraScanSettings); +}; diff --git a/src/config/yaraSettingSeeds.ts b/src/config/yaraSettingSeeds.ts new file mode 100644 index 00000000000..9d4838f014b --- /dev/null +++ b/src/config/yaraSettingSeeds.ts @@ -0,0 +1,16 @@ +import { positiveDecimalIntegerSchema } from "./positiveDecimalInteger.js"; +import { YARA_SETTING_BOUNDS } from "../domain/yara/yaraMatches.js"; + +const seed = (name: keyof typeof YARA_SETTING_BOUNDS) => + positiveDecimalIntegerSchema( + YARA_SETTING_BOUNDS[name].minimum, + YARA_SETTING_BOUNDS[name].maximum, + "must be a positive decimal integer", + ); + +/** Launch seeds of the yara settings, parsed by the shared configuration owner. */ +export const YARA_SETTING_SEEDS = { + REA_YARA_COMMAND_TIMEOUT_MS: seed("command_timeout_ms"), + REA_YARA_MAX_OUTPUT_BYTES: seed("max_output_bytes"), + REA_YARA_MAX_MATCHES: seed("max_matches"), +} as const; diff --git a/src/contracts/toolContracts.ts b/src/contracts/toolContracts.ts index d5496494b19..f9a5329444b 100644 --- a/src/contracts/toolContracts.ts +++ b/src/contracts/toolContracts.ts @@ -17,6 +17,7 @@ import { DEB_PACKAGE_TOOL_CONTRACTS } from "./deb/debPackageToolContracts.js"; import { NUGET_NUPKG_TOOL_CONTRACTS } from "./nuget/nupkgToolContracts.js"; import { VSIX_PACKAGE_TOOL_CONTRACTS } from "./vsix/vsixPackageToolContracts.js"; import { OCI_IMAGE_LAYOUT_TOOL_CONTRACTS } from "./oci/ociImageLayoutToolContracts.js"; +import { YARA_TOOL_CONTRACTS } from "./yara/yaraToolContracts.js"; import { ERLANG_BEAM_TOOL_CONTRACTS } from "./erlang/beamToolContracts.js"; import { V8_CODE_CACHE_TOOL_CONTRACTS } from "./v8/v8CodeCacheToolContracts.js"; import { MAVEN_GRADLE_METADATA_TOOL_CONTRACTS } from "./java/mavenGradleMetadataToolContracts.js"; @@ -80,6 +81,7 @@ const CATALOG_CONTRACT_GROUPS = { NUGET_NUPKG_TOOL_CONTRACTS, VSIX_PACKAGE_TOOL_CONTRACTS, OCI_IMAGE_LAYOUT_TOOL_CONTRACTS, + YARA_TOOL_CONTRACTS, ERLANG_BEAM_TOOL_CONTRACTS, V8_CODE_CACHE_TOOL_CONTRACTS, MAVEN_GRADLE_METADATA_TOOL_CONTRACTS, diff --git a/src/contracts/toolFamilies.ts b/src/contracts/toolFamilies.ts index de1dc0a45ee..a7168c45810 100644 --- a/src/contracts/toolFamilies.ts +++ b/src/contracts/toolFamilies.ts @@ -54,6 +54,7 @@ export const TOOL_FAMILY_DEFINITIONS = [ ...TOOL_CONTRACT_GROUPS.NUGET_NUPKG_TOOL_CONTRACTS, ...TOOL_CONTRACT_GROUPS.VSIX_PACKAGE_TOOL_CONTRACTS, ...TOOL_CONTRACT_GROUPS.OCI_IMAGE_LAYOUT_TOOL_CONTRACTS, + ...TOOL_CONTRACT_GROUPS.YARA_TOOL_CONTRACTS, ...TOOL_CONTRACT_GROUPS.ERLANG_BEAM_TOOL_CONTRACTS, ...TOOL_CONTRACT_GROUPS.V8_CODE_CACHE_TOOL_CONTRACTS, ...TOOL_CONTRACT_GROUPS.MAVEN_GRADLE_METADATA_TOOL_CONTRACTS, diff --git a/src/contracts/yara/yaraToolContracts.ts b/src/contracts/yara/yaraToolContracts.ts new file mode 100644 index 00000000000..ddd3a43ff91 --- /dev/null +++ b/src/contracts/yara/yaraToolContracts.ts @@ -0,0 +1,37 @@ +import { + inspectYaraMatchesInputSchema, + yaraMatchesSchema, +} from "../../domain/yara/yaraMatches.js"; +import type { ToolContract } from "../toolContractTypes.js"; +import { toolContractMetadata, toolEffects } from "../toolEffects.js"; +import { evidenceResultOf } from "../toolOutputSchemaPrimitives.js"; + +/** Caller-supplied YARA rules run by the caller-selected yara command. */ +export const YARA_TOOL_CONTRACTS = [ + { + name: "inspect_yara_matches", + cli: true, + ...toolContractMetadata( + "inspect_yara_matches", + toolEffects({ + mutatesSession: true, + launchesProcess: true, + writesFilesystem: true, + }), + ), + kind: "artifact-provider", + description: + "Scan one local file with caller-supplied YARA rule files using the installed yara command (REA_YARA_COMMAND or yara on PATH). The file is read, never executed; REA bundles no rules and downloads nothing. Returns matching rules with tags, metadata and string match offsets, bound to the file SHA-256 and each rule file SHA-256. String matches beyond max_matches are counted and coverage is partial. Rule compile errors are input errors naming the rule file. command_timeout_ms, max_output_bytes and max_matches also have runtime settings; max_file_bytes bounds the scanned file and each rule file. Complete Evidence is the result.", + inputSchema: inspectYaraMatchesInputSchema, + outputSchema: evidenceResultOf(yaraMatchesSchema), + examples: [ + { + title: "Scan a sample with a local rule file", + input: { + path: "/artifacts/sample.bin", + rule_paths: ["/rules/packers.yar"], + }, + }, + ], + }, +] as const satisfies readonly ToolContract[]; diff --git a/src/domain/analysisErrorBase.ts b/src/domain/analysisErrorBase.ts index ce010852dcd..98cd162521d 100644 --- a/src/domain/analysisErrorBase.ts +++ b/src/domain/analysisErrorBase.ts @@ -726,6 +726,7 @@ import type { CutterBridgeDiscovery } from "./cutterDiscovery.js"; import type { WebTraceObservation } from "./webTraceObservation.js"; import type { WebArtifactAcquisition } from "./webArtifactAcquisition.js"; +import type { YaraMatches } from "./yara/yaraMatches.js"; /** Provider-neutral evidence collected before a typed analysis failure. */ export type AnalysisPartialObservation = @@ -802,4 +803,5 @@ export type AnalysisPartialObservation = | AdbActivityStartPartialObservation | AdbAcquiredFilePartialObservation | AdbPackagePullPartialObservation - | AdbDisplayPartialObservation; + | AdbDisplayPartialObservation + | YaraMatches; diff --git a/src/domain/analysisSettingDefinitions.ts b/src/domain/analysisSettingDefinitions.ts index 794b0613597..642fbfa7704 100644 --- a/src/domain/analysisSettingDefinitions.ts +++ b/src/domain/analysisSettingDefinitions.ts @@ -79,6 +79,7 @@ import { JAVASCRIPT_WORKER_HEAP_MIB_MAXIMUM, } from "./javascript/javascriptAnalysisResourceControls.js"; import { DEFAULT_WASM_COMMAND_TIMEOUT_MS } from "./wasm/wasmArtifact.js"; +import { YARA_SETTING_BOUNDS } from "./yara/yaraMatches.js"; import { BOUNDED_PRODUCER_LIMITS } from "./producerResourceLimits.js"; import { DEFAULT_ARTIFACT_MEMBER_COUNT, @@ -456,6 +457,41 @@ export const ANALYSIS_SETTINGS = { operations: ["inspect_wasm_artifact"], parameter: "command_timeout_ms", }, + "yara.command_timeout_ms": { + updateMode: "runtime", + ...timer, + environment: "REA_YARA_COMMAND_TIMEOUT_MS", + defaultValue: YARA_SETTING_BOUNDS.command_timeout_ms.default_value, + minimum: YARA_SETTING_BOUNDS.command_timeout_ms.minimum, + maximum: YARA_SETTING_BOUNDS.command_timeout_ms.maximum, + provider: "yara.command", + operations: ["inspect_yara_matches"], + parameter: "command_timeout_ms", + }, + "yara.max_output_bytes": { + updateMode: "runtime", + environment: "REA_YARA_MAX_OUTPUT_BYTES", + defaultValue: YARA_SETTING_BOUNDS.max_output_bytes.default_value, + minimum: YARA_SETTING_BOUNDS.max_output_bytes.minimum, + maximum: YARA_SETTING_BOUNDS.max_output_bytes.maximum, + unit: "bytes", + appliesAt: "next_operation", + provider: "yara.command", + operations: ["inspect_yara_matches"], + parameter: "max_output_bytes", + }, + "yara.max_matches": { + updateMode: "runtime", + environment: "REA_YARA_MAX_MATCHES", + defaultValue: YARA_SETTING_BOUNDS.max_matches.default_value, + minimum: YARA_SETTING_BOUNDS.max_matches.minimum, + maximum: YARA_SETTING_BOUNDS.max_matches.maximum, + unit: "count", + appliesAt: "next_operation", + provider: "yara.command", + operations: ["inspect_yara_matches"], + parameter: "max_matches", + }, "browser.timeline_retained_bytes": { updateMode: "runtime", defaultValue: DEFAULT_BROWSER_TIMELINE_RETAINED_BYTES, diff --git a/src/domain/analysisSettings.ts b/src/domain/analysisSettings.ts index f9aa4e0f706..81cb70d1f26 100644 --- a/src/domain/analysisSettings.ts +++ b/src/domain/analysisSettings.ts @@ -19,6 +19,9 @@ export interface AnalysisSettingValues { readonly "javascript.max_heap_mb": number; readonly "javascript.member_mutation_alias_states": number; readonly "wasm.command_timeout_ms": number; + readonly "yara.command_timeout_ms": number; + readonly "yara.max_output_bytes": number; + readonly "yara.max_matches": number; readonly "native.matching_representation_bytes": number; readonly "bridge.max_request_bytes": number; readonly "bridge.max_reply_bytes": number; diff --git a/src/domain/yara/yaraMatches.ts b/src/domain/yara/yaraMatches.ts new file mode 100644 index 00000000000..98590fba2a8 --- /dev/null +++ b/src/domain/yara/yaraMatches.ts @@ -0,0 +1,231 @@ +import { z } from "zod"; + +import { MAX_NODE_TIMER_DELAY_MS } from "../analysisResourceLimits.js"; +import { knownCoverageStatusSchema } from "../coverage.js"; +import { digestSchema } from "../digests.js"; +import { absoluteLocalPathStringSchema } from "../localPath.js"; +import type { AnalysisParameterLimit } from "../analysisSettings.js"; + +/** Public operation name shared by the CLI, MCP and the provider. */ +export const INSPECT_YARA_MATCHES_OPERATION = "inspect_yara_matches"; + +/** + * Bounds of the controls an analyst plausibly raises within a session. Each + * one is also a registered analysis setting with a launch seed; an explicit + * argument wins over both. + */ +export const YARA_SETTING_BOUNDS = { + command_timeout_ms: { + minimum: 1, + // Node's timer delay ceiling (signed 32-bit milliseconds). + maximum: MAX_NODE_TIMER_DELAY_MS, + default_value: 60_000, + }, + max_output_bytes: { + minimum: 4096, + maximum: 1024 * 1024 * 1024, + // Stdout is parsed as it streams; only retained matches stay in memory. + default_value: 64 * 1024 * 1024, + }, + max_matches: { + minimum: 1, + maximum: 100_000, + default_value: 256, + }, +} as const; + +/** Per-call identity-pass budget for the scanned file and each rule file. */ +export const YARA_FILE_BYTES = { + minimum: 1, + // The file is hashed in one streaming pass and memory-mapped by yara, so the + // bound limits work rather than REA memory. + maximum: 64 * 1024 * 1024 * 1024, + default_value: 2 * 1024 * 1024 * 1024, +} as const; + +/** + * Fixed contract ceiling on rule files in one call. Each file is one + * argument to the yara command line, is hashed before the scan, and holds + * one open descriptor until the scan ends. + */ +export const MAX_YARA_RULE_FILES = 64; + +/** The per-call `max_file_bytes` limit that refused a selected file. */ +export const yaraFileBytesLimit = ( + effectiveValue: number, + requiredValue?: number, +): AnalysisParameterLimit => ({ + control_kind: "parameter", + parameter: "max_file_bytes", + effective_value: effectiveValue, + unit: "bytes", + ...YARA_FILE_BYTES, + applies_at: "next_call", + ...(requiredValue === undefined ? {} : { required_value: requiredValue }), +}); + +const settingParameter = ( + name: keyof typeof YARA_SETTING_BOUNDS, + description: string, +) => + z + .number() + .int() + .min(YARA_SETTING_BOUNDS[name].minimum) + .max(YARA_SETTING_BOUNDS[name].maximum) + .exactOptional() + .describe( + `${description} (default ${String(YARA_SETTING_BOUNDS[name].default_value)}, range ${String(YARA_SETTING_BOUNDS[name].minimum)}..${String(YARA_SETTING_BOUNDS[name].maximum)}). Overrides yara.${name} for this call.`, + ); + +/** One scan of a caller-selected local file with caller-supplied rule files. */ +export const inspectYaraMatchesInputSchema = z.strictObject({ + path: absoluteLocalPathStringSchema.describe( + "Absolute path to the local file to scan; it is read, never executed", + ), + rule_paths: z + .array(absoluteLocalPathStringSchema) + .min(1) + .max(MAX_YARA_RULE_FILES) + .describe( + `Absolute paths to YARA rule source files, compiled together in this order (at most ${String(MAX_YARA_RULE_FILES)})`, + ), + fast_scan: z + .boolean() + .exactOptional() + .describe( + "Pass yara --fast-scan: stop at the first match of each string, so string match counts are lower bounds", + ), + max_matches: settingParameter( + "max_matches", + "String matches retained inline across all rules; later matches are counted but not listed", + ), + max_output_bytes: settingParameter( + "max_output_bytes", + "Bytes of yara stdout parsed, and of stderr retained; exceeding it stops the scan", + ), + command_timeout_ms: settingParameter( + "command_timeout_ms", + "Deadline in milliseconds for the yara command", + ), + max_file_bytes: z + .number() + .int() + .min(YARA_FILE_BYTES.minimum) + .max(YARA_FILE_BYTES.maximum) + .exactOptional() + .describe( + `Largest scanned file or rule file admitted (default ${String(YARA_FILE_BYTES.default_value)} bytes)`, + ), +}); +export type InspectYaraMatchesInput = z.output< + typeof inspectYaraMatchesInputSchema +>; + +const nonnegativeSafeInteger = z.int().nonnegative(); +const fileIdentity = z.strictObject({ + path: z.string().min(1), + sha256: digestSchema, + bytes: nonnegativeSafeInteger, +}); + +/** One metadata entry as declared in the rule, in declaration order. */ +export const yaraMetaSchema = z.discriminatedUnion("type", [ + z.strictObject({ + identifier: z.string().min(1), + type: z.literal("string"), + value: z.string(), + }), + z.strictObject({ + identifier: z.string().min(1), + type: z + .literal("bytes") + .describe("A string value that is not valid UTF-8, as lowercase hex"), + value: z.string().regex(/^(?:[0-9a-f]{2})*$/u), + }), + z.strictObject({ + identifier: z.string().min(1), + type: z.literal("integer"), + value: z + .union([z.int(), z.string().regex(/^-?\d+$/u)]) + .describe("A number, or decimal text beyond the safe integer range"), + }), + z.strictObject({ + identifier: z.string().min(1), + type: z.literal("boolean"), + value: z.boolean(), + }), +]); +export type YaraMeta = z.infer; + +/** One string match yara reported, located by file offset. */ +export const yaraStringMatchSchema = z.strictObject({ + identifier: z.string().regex(/^\$[A-Za-z0-9_]*$/u), + file_offset: nonnegativeSafeInteger, + length: nonnegativeSafeInteger, + data: z + .string() + .describe( + "Matched bytes as yara displays them: printable ASCII, \\xNN escapes for other bytes of text and regex strings, spaced hex for hex strings; yara may shorten long matches", + ), +}); +export type YaraStringMatch = z.infer; + +/** One matching rule with its declared tags and metadata. */ +export const yaraRuleMatchSchema = z.strictObject({ + rule: z.string().min(1), + tags: z.array(z.string().min(1)), + meta: z.array(yaraMetaSchema), + string_match_count: nonnegativeSafeInteger.describe( + "Every string match yara reported for this rule, including unlisted ones", + ), + strings: z.array(yaraStringMatchSchema), +}); +export type YaraRuleMatch = z.infer; + +const settingSource = z.enum(["default", "setting", "runtime", "request"]); +const effectiveLimit = z.strictObject({ + value: nonnegativeSafeInteger, + source: settingSource, +}); + +/** Matching rules for one scanned file, bound to the file and rule digests. */ +export const yaraMatchesSchema = z.strictObject({ + artifact: fileIdentity, + rule_files: z.array(fileIdentity).min(1), + fast_scan: z.boolean(), + matches: z.array(yaraRuleMatchSchema), + coverage: z.strictObject({ + status: knownCoverageStatusSchema.describe( + "partial when string matches beyond max_matches are unlisted", + ), + matched_rules: nonnegativeSafeInteger, + string_matches: nonnegativeSafeInteger, + listed_string_matches: nonnegativeSafeInteger, + }), + limits: z.strictObject({ + max_matches: effectiveLimit, + max_output_bytes: effectiveLimit, + command_timeout_ms: effectiveLimit, + max_file_bytes: nonnegativeSafeInteger, + }), + warnings: z + .array(z.string().min(1)) + .describe("Compiler and scan warnings yara printed, verbatim"), + limitations: z.array(z.string().min(1)).min(1), +}); +export type YaraMatches = z.infer; +export type YaraSettingSource = z.infer; + +/** One accepted control value and where it came from. */ +export interface YaraSettingValue { + readonly value: number; + readonly source: YaraSettingSource; +} + +/** The resolved controls of one scan, in the shape the result reports them. */ +export interface YaraScanSettings { + readonly max_matches: YaraSettingValue; + readonly max_output_bytes: YaraSettingValue; + readonly command_timeout_ms: YaraSettingValue; +} diff --git a/src/ports/yara/YaraMatchesPort.ts b/src/ports/yara/YaraMatchesPort.ts new file mode 100644 index 00000000000..0808b2f928b --- /dev/null +++ b/src/ports/yara/YaraMatchesPort.ts @@ -0,0 +1,27 @@ +import type { + ExecutionOptions, + ProviderIdentity, +} from "../AnalysisProvider.js"; +import type { AnalysisError } from "../../domain/analysisErrorBase.js"; +import type { Result } from "../../domain/result.js"; +import type { + InspectYaraMatchesInput, + YaraMatches, + YaraScanSettings, +} from "../../domain/yara/yaraMatches.js"; + +/** One admitted scan: the validated request and its resolved controls. */ +export interface YaraScanRequest { + readonly input: InspectYaraMatchesInput; + readonly settings: YaraScanSettings; +} + +/** Runs the caller-selected yara command against one stable local file. */ +export interface YaraMatchesPort { + readonly identity: ProviderIdentity; + close(): Promise; + inspect( + request: YaraScanRequest, + options?: ExecutionOptions, + ): Promise>; +} diff --git a/src/providers/offlineArtifactFailure.ts b/src/providers/offlineArtifactFailure.ts index 609487e565a..9b9fd3b4073 100644 --- a/src/providers/offlineArtifactFailure.ts +++ b/src/providers/offlineArtifactFailure.ts @@ -2,6 +2,7 @@ import { ArtifactReaderFailure, projectOwnedArtifactInputFailure, type ArtifactFilePrimaryFacts, + type RequestField, artifactOperationReason, } from "../resources/index.js"; import type { AnalysisError } from "../domain/analysisErrorBase.js"; @@ -20,7 +21,7 @@ export type OfflineArtifactDialectOptions = { readonly path: string; readonly description: string; /** The request field that selected the file; `path` when omitted. */ - readonly field?: string; + readonly field?: RequestField; /** * Format- or provider-specific errors examined before the shared * `ParseFailureError`, owned input, and selected-file projections. diff --git a/src/server/createServer.ts b/src/server/createServer.ts index 19e00b720ac..be9a2e831f5 100644 --- a/src/server/createServer.ts +++ b/src/server/createServer.ts @@ -218,6 +218,7 @@ export const createServer = ( nugetNupkg, vsixPackage, ociImageLayout, + yaraMatches, pythonPyc, debPackage, mavenGradleMetadata, @@ -440,6 +441,7 @@ export const createServer = ( nugetNupkg, vsixPackage, ociImageLayout, + yaraMatches, pythonPyc, debPackage, erlangBeam, diff --git a/src/server/offlineInspectionToolBindings.ts b/src/server/offlineInspectionToolBindings.ts index 8457b194bad..b51a373bf83 100644 --- a/src/server/offlineInspectionToolBindings.ts +++ b/src/server/offlineInspectionToolBindings.ts @@ -40,6 +40,7 @@ import type { SqliteDatabaseService } from "../application/sqlite/SqliteDatabase import type { V8CodeCacheService } from "../application/v8CodeCache/V8CodeCacheService.js"; import type { VsixPackageService } from "../application/vsix/VsixPackageService.js"; import type { WasmArtifactService } from "../application/wasm/WasmArtifactService.js"; +import type { YaraMatchesService } from "../application/yara/YaraMatchesService.js"; import { compareWasmInterfaces } from "../application/wasm/WasmInterfaceComparisonService.js"; import { ok } from "../domain/result.js"; import type { ContractToolBindings } from "./contractToolBindings.js"; @@ -240,6 +241,12 @@ export const OFFLINE_INSPECTION_TOOL_BINDINGS = { summary: (input, options) => service.inspect(input, options), }, })) satisfies Bind, + yaraMatches: ((service) => ({ + inspect_yara_matches: { + admission: "application", + run: (input, options) => service.inspect(input, options), + }, + })) satisfies Bind, pythonPyc: ((service) => ({ inspect_python_pyc: { admission: "application", diff --git a/src/yara/YaraMatchesProvider.ts b/src/yara/YaraMatchesProvider.ts new file mode 100644 index 00000000000..804eb521da5 --- /dev/null +++ b/src/yara/YaraMatchesProvider.ts @@ -0,0 +1,1212 @@ +import { randomUUID } from "node:crypto"; +import type { BigIntStats } from "node:fs"; +import { open, type FileHandle } from "node:fs/promises"; +import { join, posix, win32 } from "node:path"; + +import { isQualifiedCallerPath } from "../filesystem/callerPath.js"; + +import { + YARA_COMMAND_REMEDIATION, + YARA_PROVIDER_IDENTITY, +} from "./YaraProviderIdentity.js"; +import { + parseYaraDiagnostics, + yaraMatchOutputSink, + YaraMatchOutputParser, + type YaraCompileErrorKind, + type YaraDiagnostics, + type YaraParsedMatches, +} from "./YaraOutput.js"; +import { + createYaraIncludeRewriter, + type YaraIncludeRewriter, +} from "./YaraRuleIncludeRewrite.js"; +import { + AnalysisCleanupLease, + ArtifactReaderFailure, + ArtifactResourceScope, + artifactFilePrimaryFacts, + assertArtifactReadActive, + assertStableArtifactState, + closeArtifactResources, + completedStableArtifactObservation, + completedStableArtifactStream, + projectStableArtifactFailure, + streamStableArtifact, + withArtifactFileHandle, + type RequestField, +} from "../resources/index.js"; +import { + OwnedCommandFailure, + prepareOwnedCommand, + runOwnedCommand, +} from "../process/OwnedCommand.js"; +import { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js"; +import { privateWorkspaceFailure } from "../process/privateWorkspaceFailure.js"; +import type { + OwnedProviderProcessSpawnOptions, + ProviderProcessSnapshot, + SpawnedOwnedProviderProcess, +} from "../process/ProviderProcess.js"; +import { providerOutcomeOf } from "../process/ProviderOutcome.js"; +import { capturedProviderOutput } from "../process/capturedProviderOutput.js"; +import { describeLaunchFailure } from "../process/launchFailure.js"; +import { + classifyProviderOutcome, + type ProviderOutcomeContext, +} from "../process/classifyProviderOutcome.js"; +import { snapshotEnvironment } from "../process/snapshotEnvironment.js"; +import { + processInspectionCancellationError, + retainArtifactCommandCleanup, + retainProcessInspectionCleanup, +} from "../providers/OwnedCommandCleanup.js"; +import { classifyProviderFailure } from "../providers/classifyProviderFailure.js"; +import { offlineArtifactFailureDialect } from "../providers/offlineArtifactFailure.js"; +import { + AnalysisError, + primaryAnalysisError, +} from "../domain/analysisErrorBase.js"; +import type { AnalysisErrorOptions } from "../domain/analysisErrorBase.js"; +import { analysisErrorWithCancellation } from "../domain/analysisErrorCancellation.js"; +import { + AnalysisCapabilityUnavailableError, + AnalysisInputError, + AnalysisOutputError, + cancelledBy, + carriedReason, +} from "../domain/analysisErrorCore.js"; +import { decodeLimit } from "../domain/parseFailure.js"; +import { parseLimitConstraint } from "../domain/parseFailureAnalysisError.js"; +import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js"; +import { analysisSettingLimit } from "../domain/analysisSettingDefinitions.js"; +import { ProviderAdapterError } from "../domain/providerAdapterError.js"; +import { ProviderCleanupError } from "../domain/providerCleanupError.js"; +import { + RuntimeControlUnavailableError, + runtimeControlCapabilityError, +} from "../domain/runtimeControlUnavailableError.js"; +import { err, ok, type Result } from "../domain/result.js"; +import { + INSPECT_YARA_MATCHES_OPERATION, + YARA_FILE_BYTES, + yaraFileBytesLimit, + type InspectYaraMatchesInput, + type YaraMatches, + type YaraScanSettings, +} from "../domain/yara/yaraMatches.js"; +import type { + YaraMatchesPort, + YaraScanRequest, +} from "../ports/yara/YaraMatchesPort.js"; +import type { ExecutionOptions } from "../ports/AnalysisProvider.js"; +import { HOST_PLATFORM } from "../platform/HostPlatform.js"; + +const OPERATION = INSPECT_YARA_MATCHES_OPERATION; +const PROVIDER_ID = YARA_PROVIDER_IDENTITY.id; +/** Names the admission whose byte limit refused a selected file. */ +const YARA_SCAN_FORMAT = "yara-scan"; + +/** + * yara options: print matching strings with their lengths, metadata and + * tags, and suppress console-module output so stdout carries only matches. + */ +const BASE_ARGUMENTS = ["-s", "-L", "-m", "-g", "-q"] as const; + +/** Starts the yara process under owned supervision; tests substitute one. */ +export type YaraLauncher = ( + options: OwnedProviderProcessSpawnOptions, +) => Promise; + +/** The executable to launch, or why the configured command cannot be used. */ +export type YaraCommandSelection = () => Result; + +export interface YaraMatchesProviderOptions { + readonly environment: Readonly; + readonly selectCommand: YaraCommandSelection; + readonly platform?: NodeJS.Platform; + readonly launcher?: YaraLauncher; + readonly createRuntime?: () => Promise< + Pick + >; + readonly openSnapshotFile?: (path: string) => Promise; +} + +/** The selected file a failed phase was reading. */ +interface ReadPhase { + readonly path: string; + readonly field: RequestField; + readonly description: string; +} + +/** One selected file's completed digest and byte count before later failures. */ +interface CompletedFileIdentity { + readonly path: string; + readonly sha256: string; + readonly bytes: number; +} + +/** Completed admitted file identities accumulated during one scan call. */ +interface CompletedAdmittedFiles { + readonly rules: Map; + target: CompletedFileIdentity | undefined; +} + +/** One selected file staged into the private snapshot with its hashed identity. */ +interface StagedSnapshotFile { + readonly callerPath: string; + readonly snapshotPath: string; + readonly sha256: string; + readonly bytes: number; + readonly state: BigIntStats; +} + +/** Owned snapshot inputs passed to yara and mapped back to caller paths. */ +interface StagedScanInputs { + readonly target: StagedSnapshotFile; + readonly rules: readonly StagedSnapshotFile[]; + readonly fastScan: boolean; +} + +/** + * The namespace every rule file is compiled into. yara 4 reads a rule + * argument as a file path, relative to its working directory, when that + * file exists, and otherwise splits it at the first `:` into NAMESPACE:FILE. + * With this prefix and the working directory at the filesystem root, the whole + * argument names no file, so yara takes the explicit namespace and reads the + * rest of the argument verbatim as the snapshot path even if TMPDIR contains `:`. + */ +const RULE_NAMESPACE = "rea"; + +/** The argv yara receives; every snapshot path is absolute, so none parses as an option. */ +const yaraArguments = (staged: StagedScanInputs): readonly string[] => [ + ...BASE_ARGUMENTS, + ...(staged.fastScan ? ["-f"] : []), + ...staged.rules.map((rule) => `${RULE_NAMESPACE}:${rule.snapshotPath}`), + staged.target.snapshotPath, +]; + +/** + * yara 4.x `cli/yara.c` ends through `exit_with_code(EXIT_FAILURE)` for compile + * errors, `--fail-on-warnings` and scan errors, and C's EXIT_FAILURE is 1. + */ +const YARA_EXIT_FAILURE = 1; + +/** The rule file paths yara was given, as it names them in diagnostics. */ +const ruleSnapshotPaths = (staged: StagedScanInputs): readonly string[] => + staged.rules.map((rule) => rule.snapshotPath); + +/** The selected rule file yara named in a compile error, if it is one. */ +const ruleFileIndex = (staged: StagedScanInputs, source: string): number => { + const prefix = `${RULE_NAMESPACE}:`; + const named = source.startsWith(prefix) + ? source.slice(prefix.length) + : source; + return staged.rules.findIndex((rule) => rule.snapshotPath === named); +}; + +/** Replace internal snapshot paths with the caller's selected paths in yara text. */ +const restoreCallerPaths = (text: string, staged: StagedScanInputs): string => { + let restored = text; + for (const rule of staged.rules) { + restored = restored + .replaceAll(`${RULE_NAMESPACE}:${rule.snapshotPath}`, rule.callerPath) + .replaceAll(rule.snapshotPath, rule.callerPath); + } + return restored.replaceAll( + staged.target.snapshotPath, + staged.target.callerPath, + ); +}; + +/** + * Pre-flight path checks that cannot be expressed in the portable schema: + * - yara prints one match per line and names the scanned path on each rule + * line, so a line break in a selected path makes its output ambiguous. + * - On Windows, the child runs from the scanned path's root (for example + * `D:\`). A drive-relative rooted path such as `\rules\packers.yar` would + * resolve against REA's current drive when hashing and against the child's + * drive when yara opens it, so Windows paths must be drive-qualified or UNC. + */ +const pathInputRefusal = ( + input: InspectYaraMatchesInput, + platform: NodeJS.Platform, +): AnalysisInputError | undefined => { + const fields: { path: (string | number)[]; value: string }[] = [ + { path: ["path"], value: input.path }, + ...input.rule_paths.map((value, index) => ({ + path: ["rule_paths", index], + value, + })), + ]; + const issues: { + path: (string | number)[]; + reason: "invalid_value"; + message: string; + }[] = []; + let hasLineBreak = false; + let hasUnqualifiedWindowsPath = false; + for (const { path, value } of fields) { + if (/[\r\n]/u.test(value)) { + hasLineBreak = true; + issues.push({ + path, + reason: "invalid_value", + message: + "The path contains a line break, which yara's line-oriented output cannot represent.", + }); + } + if (platform === "win32" && !isQualifiedCallerPath(value, platform)) { + hasUnqualifiedWindowsPath = true; + issues.push({ + path, + reason: "invalid_value", + message: + "On Windows, paths must be drive-qualified (for example C:\\...) or UNC paths so they do not depend on the working drive.", + }); + } + } + if (issues.length === 0) return undefined; + const remediation = [ + ...(hasLineBreak + ? ["Rename or link the file to a path without line breaks."] + : []), + ...(hasUnqualifiedWindowsPath + ? ["Pass drive-qualified or UNC paths for path and rule_paths."] + : []), + ].join(" "); + return new AnalysisInputError( + OPERATION, + { + conformsToInputContract: true, + remediationAction: `${remediation} Then retry.`, + }, + issues, + ); +}; + +/** The repair each kind of compile error needs, in the order they are reported. */ +const COMPILE_ERROR_REMEDIATION: Readonly< + Record +> = { + include: + "Make each included file exist and be readable; a relative include resolves against the directory of the rule file that includes it. Or remove the include.", + syntax: "Fix the rule syntax at the reported line.", + undefined: + "Define the identifier or string, or import the module that provides it; rules that need external variables or module data cannot be compiled by this tool.", + duplicate: + "Names must be unique in their scope: rule names across all selected files and their includes, and string, tag and metadata identifiers within their rule. Rename or remove the duplicated identifier at the reported source and line.", + unreadable_file: + "Select a rule file that exists and is readable, or remove it from rule_paths.", + other: "Fix the reported rule source, or remove that file from rule_paths.", +}; + +/** One repair sentence per kind present, then the retry. */ +const compileRemediation = (diagnostics: YaraDiagnostics): string => + [ + ...new Set( + diagnostics.compileErrors.map( + ({ kind }) => COMPILE_ERROR_REMEDIATION[kind], + ), + ), + "Then retry.", + ].join(" "); + +/** Lines yara wrote that match no documented form, kept for the caller. */ +const unrecognizedDiagnostics = ( + diagnostics: YaraDiagnostics, + staged: StagedScanInputs, +): Readonly> => + diagnostics.unrecognized.length === 0 + ? {} + : { + unrecognized_stderr_lines: diagnostics.unrecognized.map((line) => + restoreCallerPaths(line, staged), + ), + }; + +/** A rule source yara refused to compile is the caller's selection. */ +const ruleCompileError = ( + diagnostics: YaraDiagnostics, + staged: StagedScanInputs, + details: AnalysisErrorOptions, +): AnalysisInputError => { + const compileErrors = diagnostics.compileErrors.map((failure) => { + const index = + failure.source === null ? -1 : ruleFileIndex(staged, failure.source); + const source = + failure.source === null + ? null + : index === -1 + ? restoreCallerPaths(failure.source, staged) + : staged.rules[index]!.callerPath; + return { + index, + failure: { + ...failure, + source, + message: restoreCallerPaths(failure.message, staged), + }, + }; + }); + const issues = compileErrors.map(({ index, failure }) => ({ + path: index === -1 ? ["rule_paths"] : ["rule_paths", index], + reason: "invalid_value" as const, + message: `${failure.source === null ? "" : `${failure.source}${failure.line === null ? "" : `(${String(failure.line)})`}: `}${failure.rule === null ? "" : `rule "${failure.rule}": `}${failure.message}`, + })); + return new AnalysisInputError( + OPERATION, + { + ...details, + conformsToInputContract: true, + userMessage: `yara could not compile the selected rules: ${issues.map((issue) => issue.message).join("; ")}`, + remediationAction: compileRemediation(diagnostics), + diagnostics: { + ...details.diagnostics, + compile_errors: compileErrors.map(({ failure }) => failure), + ...unrecognizedDiagnostics(diagnostics, staged), + }, + }, + issues, + ); +}; + +/** What one yara outcome means; owner-observed facts are shared. */ +const yaraOutcomeContext = ( + staged: StagedScanInputs, + settings: YaraScanSettings, + command: string, +): ProviderOutcomeContext => ({ + providerId: PROVIDER_ID, + operation: OPERATION, + capturedOutput: capturedProviderOutput, + details: { diagnostics: { command } }, + timeout: { + ms: settings.command_timeout_ms.value, + limit: analysisSettingLimit( + "yara.command_timeout_ms", + settings.command_timeout_ms.value, + settings.command_timeout_ms.source, + ), + }, + outputLimit: { + reason: `yara output exceeded max_output_bytes (${String(settings.max_output_bytes.value)} bytes on stdout or stderr).`, + limits: { max_output_bytes: settings.max_output_bytes.value }, + recovery: { retryable: false }, + limit: analysisSettingLimit( + "yara.max_output_bytes", + settings.max_output_bytes.value, + settings.max_output_bytes.source, + ), + }, + launchUnavailable: (failure, details) => { + const reason = + failure.kind === "missing" + ? `The yara command ${command} was not found (${describeLaunchFailure(failure)}).` + : `The yara command ${command} could not be started (${describeLaunchFailure(failure)}).`; + return new AnalysisCapabilityUnavailableError( + PROVIDER_ID, + OPERATION, + reason, + { + ...details, + userMessage: `${reason} ${YARA_COMMAND_REMEDIATION}`, + remediationAction: YARA_COMMAND_REMEDIATION, + }, + ); + }, + dialect: (outcome, details, unclassified) => { + const diagnostics = parseYaraDiagnostics( + outcome.output?.snapshot.stderr.text ?? "", + staged.target.snapshotPath, + ruleSnapshotPaths(staged), + ); + // yara exits EXIT_FAILURE after printing why it refused the rules or the file. + const reported = + outcome.kind === "exited" && + outcome.exitCode === YARA_EXIT_FAILURE && + outcome.signal === null && + !outcome.stopRequested && + outcome.output?.truncated === false; + if (reported && diagnostics.compileErrors.length > 0) + return ruleCompileError(diagnostics, staged, details); + return unclassified({ + diagnostics: { + ...(diagnostics.scanErrors.length === 0 + ? {} + : { + scan_errors: diagnostics.scanErrors.map(({ reason }) => + restoreCallerPaths(reason, staged), + ), + }), + ...unrecognizedDiagnostics(diagnostics, staged), + }, + }); + }, +}); + +/** + * Classify one yara run through the shared command outcome owner and move + * any unresolved process cleanup to the provider scope, which retries it + * before the next scan and on close. + */ +const yaraCommandFailure = ( + cause: unknown, + context: ProviderOutcomeContext, + resources: ArtifactResourceScope, +) => { + if (cause instanceof AnalysisError) return cause; + const outcome = providerOutcomeOf(cause); + // A command that exited 0 failed only because its cleanup is unproven. + if ( + outcome?.kind === "exited" && + outcome.exitCode === 0 && + outcome.signal === null + ) { + const [cleanup, ...more] = retainArtifactCommandCleanup( + cause, + resources, + OPERATION, + outcome.output === undefined + ? undefined + : { capturedOutput: capturedProviderOutput(outcome.output.snapshot) }, + ); + if (cleanup !== undefined) + return more.reduce( + (primary, failure) => + analysisErrorWithCleanupDependencies(primary, failure, OPERATION), + cleanup, + ); + } + const primary = + processInspectionCancellationError(cause, OPERATION) ?? + (outcome === undefined + ? new ProviderAdapterError(PROVIDER_ID, OPERATION, { cause }) + : classifyProviderOutcome(outcome, context)); + return retainProcessInspectionCleanup(cause, primary, resources, OPERATION); +}; + +interface CompletedScan { + readonly parsed: YaraParsedMatches; + readonly warnings: readonly string[]; +} + +const buildYaraMatchesReport = ( + input: InspectYaraMatchesInput, + staged: StagedScanInputs, + settings: YaraScanSettings, + maxFileBytes: number, + scan: CompletedScan, +): YaraMatches => ({ + artifact: { + path: input.path, + sha256: staged.target.sha256, + bytes: staged.target.bytes, + }, + rule_files: staged.rules.map((rule) => ({ + path: rule.callerPath, + sha256: rule.sha256, + bytes: rule.bytes, + })), + fast_scan: input.fast_scan === true, + matches: [...scan.parsed.matches], + coverage: { + status: + scan.parsed.listedStringMatches < scan.parsed.stringMatches + ? "partial" + : "complete", + matched_rules: scan.parsed.matches.length, + string_matches: scan.parsed.stringMatches, + listed_string_matches: scan.parsed.listedStringMatches, + }, + limits: { ...settings, max_file_bytes: maxFileBytes }, + warnings: [...scan.warnings], + limitations: limitations(input, scan.parsed, settings), +}); + +const limitations = ( + input: InspectYaraMatchesInput, + parsed: YaraParsedMatches, + settings: YaraScanSettings, +): string[] => [ + "REA ran the caller-selected yara command; its implementation and version are not observed.", + "The scanned file and rule files are copied into an owned snapshot while computing their SHA-256 digests, and yara reads only those snapshot files; files included by rules and module data that yara reads are not bound to this Evidence.", + "Only matching rules are reported; a rule that is absent did not match this file under these rules.", + "String data is yara's display text and may be shortened; read file_offset and length from the artifact for the exact bytes.", + ...(parsed.listedStringMatches < parsed.stringMatches + ? [ + `${String(parsed.stringMatches - parsed.listedStringMatches)} of ${String(parsed.stringMatches)} string matches are counted but not listed because max_matches is ${String(settings.max_matches.value)}.`, + ] + : []), + ...(input.fast_scan === true + ? [ + "fast_scan stops at the first match of each string, so string match counts are lower bounds.", + ] + : []), +]; + +/** + * Per-scan cleanup owner: closes child file handles and any retained command + * before removing the private snapshot root, and retries in that order. + */ +class YaraScanSnapshot { + readonly files = new ArtifactResourceScope(); + #rootClosed = false; + + constructor(readonly root: Pick) {} + + get path(): string { + return this.root.path; + } + + get hasPendingFiles(): boolean { + return this.files.hasPending; + } + + get cleanupResources(): readonly string[] { + return [ + ...new Set([ + ...this.files.cleanupResources, + ...(this.#rootClosed ? [] : [this.root.path]), + ]), + ]; + } + + async close(): Promise { + await this.files.close(); + if (!this.#rootClosed) { + await this.root.close(); + this.#rootClosed = true; + } + } +} + +/** Runs caller-supplied YARA rules against one stable local file. */ +export class YaraMatchesProvider implements YaraMatchesPort { + readonly identity = YARA_PROVIDER_IDENTITY; + readonly #resources = new ArtifactResourceScope(); + + constructor(readonly options: YaraMatchesProviderOptions) {} + + /** Retry retained command, snapshot, and descriptor cleanup. */ + close(): Promise { + return closeArtifactResources( + () => this.#resources.close(), + YARA_PROVIDER_IDENTITY, + OPERATION, + ); + } + + async inspect( + { input, settings }: YaraScanRequest, + options?: ExecutionOptions, + ): Promise> { + const signal = options?.signal; + const platform = this.options.platform ?? HOST_PLATFORM.platform; + const maxFileBytes = input.max_file_bytes ?? YARA_FILE_BYTES.default_value; + const refusal = pathInputRefusal(input, platform); + if (refusal !== undefined) return err(refusal); + const command = this.options.selectCommand(); + if (!command.ok) return err(command.error); + let phase: ReadPhase | undefined; + const completedFiles: CompletedAdmittedFiles = { + rules: new Map(), + target: undefined, + }; + try { + return await this.#resources.run(async () => { + const snapshot = new YaraScanSnapshot( + await this.#createRuntime(platform), + ); + let outcome: + | { readonly kind: "completed"; readonly value: YaraMatches } + | { readonly kind: "failed"; readonly cause: unknown }; + try { + outcome = { + kind: "completed", + value: await this.#inspectInSnapshot( + snapshot, + command.value, + input, + settings, + maxFileBytes, + platform, + signal, + (next) => { + phase = next; + }, + completedFiles, + ), + }; + } catch (cause: unknown) { + outcome = { kind: "failed", cause }; + } + const scanLease = AnalysisCleanupLease.forCloseOwner( + snapshot, + snapshot.path, + ); + const scanOwner = { + kind: "lease" as const, + resource: snapshot.path, + lease: scanLease, + }; + const completed = + outcome.kind === "completed" ? outcome.value : undefined; + const cleanupOutcome = (): + | { readonly kind: "completed" } + | { readonly kind: "failed"; readonly cause: unknown } => { + if (outcome.kind === "failed") + return { kind: "failed", cause: outcome.cause }; + if (signal?.aborted) + return { + kind: "failed", + cause: new ArtifactReaderFailure( + "cancelled", + "Artifact read cancelled", + { cause: signal.reason, partialObservation: outcome.value }, + ), + }; + return { kind: "completed" }; + }; + const composeSnapshotCleanup = ( + primary: AnalysisError, + lease: AnalysisCleanupLease, + failure: { readonly reason: string; readonly cause?: unknown }, + ): AnalysisError => { + const scanCleanup = new ProviderCleanupError( + PROVIDER_ID, + [snapshot.path], + { reason: failure.reason }, + { + operation: OPERATION, + ...(failure.cause === undefined ? {} : { cause: failure.cause }), + }, + ); + scanCleanup.bindCleanupResourceOwner(lease); + lease.bindCleanupError(scanCleanup); + return analysisErrorWithCleanupDependencies( + primary, + scanCleanup, + OPERATION, + ); + }; + // Never remove the snapshot root while child handles or the child + // process remain open; retain the ordered per-scan owner to retry + // child cleanup first and root removal second. + if (snapshot.hasPendingFiles) { + this.#resources.retain(scanOwner); + const pendingReason = `Snapshot directory ${snapshot.path} remains owned until child handles close`; + if ( + outcome.kind === "failed" && + outcome.cause instanceof AnalysisError + ) + throw composeSnapshotCleanup(outcome.cause, scanLease, { + reason: pendingReason, + }); + throw this.#resources.cleanupFailure( + cleanupOutcome(), + [ + { + kind: "failed", + cause: new Error(pendingReason), + owner: scanOwner, + lease: scanLease, + }, + ], + completed, + ); + } + const release = await this.#resources.release(scanOwner); + if (release.kind === "failed") { + if ( + outcome.kind === "failed" && + outcome.cause instanceof AnalysisError + ) + throw composeSnapshotCleanup(outcome.cause, release.lease, { + reason: ArtifactReaderFailure.cleanupObservation( + release.cause, + snapshot.path, + ).reason, + cause: release.cause, + }); + throw this.#resources.cleanupFailure( + cleanupOutcome(), + [release], + completed, + ); + } + if (outcome.kind === "failed") throw outcome.cause; + if (signal?.aborted) + throw cancelledBy(OPERATION, signal, { + partialObservation: outcome.value, + }); + return ok(outcome.value); + }); + } catch (cause: unknown) { + const failure = this.#failure( + cause, + input, + phase, + maxFileBytes, + completedFiles, + ); + return err( + signal?.aborted + ? analysisErrorWithCancellation( + failure, + cancelledBy(OPERATION, signal), + ) + : failure, + ); + } + } + + async #createRuntime( + platform: NodeJS.Platform, + ): Promise> { + try { + return this.options.createRuntime === undefined + ? await PrivateRuntimeRoot.create({ prefix: "rea-yara-", platform }) + : await this.options.createRuntime(); + } catch (cause: unknown) { + if (cause instanceof RuntimeControlUnavailableError) + throw runtimeControlCapabilityError(PROVIDER_ID, OPERATION, cause); + throw privateWorkspaceFailure(PROVIDER_ID, OPERATION, cause, null); + } + } + + async #stageFile( + sourcePath: string, + destinationPath: string, + maxFileBytes: number, + signal: AbortSignal | undefined, + snapshot: YaraScanSnapshot, + options?: { + readonly transform?: YaraIncludeRewriter; + readonly onIdentity?: (identity: { + readonly path: string; + readonly sha256: string; + readonly bytes: number; + }) => void; + }, + ): Promise { + const transform = options?.transform; + const onIdentity = options?.onIdentity; + let destHandle; + try { + destHandle = + this.options.openSnapshotFile === undefined + ? await open(destinationPath, "wx", 0o600) + : await this.options.openSnapshotFile(destinationPath); + } catch (cause: unknown) { + throw privateWorkspaceFailure( + PROVIDER_ID, + OPERATION, + cause, + snapshot.path, + ); + } + return withArtifactFileHandle( + destinationPath, + destHandle, + snapshot.files, + signal, + async (dest) => { + const writeChunk = async (bytes: Buffer): Promise => { + if (bytes.length === 0) return; + try { + await dest.writeFile(bytes); + } catch (cause: unknown) { + throw privateWorkspaceFailure( + PROVIDER_ID, + OPERATION, + cause, + snapshot.path, + ); + } + }; + let streamed; + try { + streamed = await streamStableArtifact(sourcePath, maxFileBytes, { + retainBytes: () => 0, + signal, + resourceScope: snapshot.files, + onChunk: async (chunk) => { + await writeChunk( + transform === undefined ? chunk : transform.push(chunk), + ); + }, + }); + } catch (cause: unknown) { + const completed = completedStableArtifactStream(cause); + if (completed !== undefined) + onIdentity?.({ + path: sourcePath, + sha256: completed.sha256, + bytes: completed.size, + }); + throw cause; + } + onIdentity?.({ + path: sourcePath, + sha256: streamed.sha256, + bytes: streamed.size, + }); + if (transform !== undefined) await writeChunk(transform.finish()); + const state = await dest.stat({ bigint: true }); + return { + callerPath: sourcePath, + snapshotPath: destinationPath, + sha256: streamed.sha256, + bytes: streamed.size, + state, + }; + }, + ); + } + + async #inspectInSnapshot( + snapshot: YaraScanSnapshot, + command: string, + input: InspectYaraMatchesInput, + settings: YaraScanSettings, + maxFileBytes: number, + platform: NodeJS.Platform, + signal: AbortSignal | undefined, + setPhase: (phase: ReadPhase) => void, + completedFiles: CompletedAdmittedFiles, + ): Promise { + const rulePhase = (index: number, path: string): ReadPhase => ({ + path, + field: ["rule_paths", index], + description: "rule file", + }); + const targetPhase: ReadPhase = { + path: input.path, + field: "path", + description: "file", + }; + const stagedRules: StagedSnapshotFile[] = []; + for (const [index, path] of input.rule_paths.entries()) { + setPhase(rulePhase(index, path)); + stagedRules.push( + await this.#stageFile( + path, + join(snapshot.path, `rule-${String(index)}.yar`), + maxFileBytes, + signal, + snapshot, + { + transform: createYaraIncludeRewriter(path, platform, maxFileBytes), + onIdentity: (identity) => { + completedFiles.rules.set(index, identity); + }, + }, + ), + ); + } + setPhase(targetPhase); + const stagedTarget = await this.#stageFile( + input.path, + join(snapshot.path, "target.bin"), + maxFileBytes, + signal, + snapshot, + { + onIdentity: (identity) => { + completedFiles.target = identity; + }, + }, + ); + const staged: StagedScanInputs = { + target: stagedTarget, + rules: stagedRules, + fastScan: input.fast_scan === true, + }; + const verifySnapshots = async ( + checkSignal: AbortSignal | undefined, + trackPhase: boolean, + ): Promise => { + // Verify that neither the target snapshot nor any rule snapshot was + // modified while yara ran before attributing matches to their digests. + if (trackPhase) setPhase(targetPhase); + await assertStableArtifactState( + stagedTarget.snapshotPath, + stagedTarget.state, + checkSignal, + ); + for (const [index, rule] of stagedRules.entries()) { + if (trackPhase) setPhase(rulePhase(index, rule.callerPath)); + await assertStableArtifactState( + rule.snapshotPath, + rule.state, + checkSignal, + ); + } + }; + const retainVerifiedScan = async ( + cause: unknown, + completed: CompletedScan | undefined, + ): Promise => { + if ( + completed === undefined || + !( + cause instanceof AnalysisError || + (cause instanceof ArtifactReaderFailure && + cause.reason === "cancelled") + ) + ) + return; + try { + await verifySnapshots(undefined, false); + cause.retainPartialObservation( + buildYaraMatchesReport( + input, + staged, + settings, + maxFileBytes, + completed, + ), + ); + } catch { + // Keep file checks before presenting matches as a verified report: + // if a snapshot changed or could not be re-verified, leave only the + // scanned file's snapshot hash on the primary failure. + } + }; + let observedScan: CompletedScan | undefined; + try { + const scan = await this.#scan( + command, + staged, + settings, + snapshot.files, + signal, + (completed) => { + observedScan = completed; + }, + ); + observedScan = scan; + await verifySnapshots(signal, true); + assertArtifactReadActive(signal); + return buildYaraMatchesReport( + input, + staged, + settings, + maxFileBytes, + scan, + ); + } catch (cause: unknown) { + await retainVerifiedScan(cause, observedScan); + throw cause; + } + } + + async #scan( + command: string, + staged: StagedScanInputs, + settings: YaraScanSettings, + scanResources: ArtifactResourceScope, + signal: AbortSignal | undefined, + onCompleted?: (scan: CompletedScan) => void, + ): Promise { + const parser = new YaraMatchOutputParser( + staged.target.snapshotPath, + settings.max_matches.value, + ); + const context = yaraOutcomeContext(staged, settings, command); + const maxOutputBytes = settings.max_output_bytes.value; + const platform = this.options.platform ?? HOST_PLATFORM.platform; + const pathApi = platform === "win32" ? win32 : posix; + let completed: Result | undefined; + const finalize = ( + observedSnapshot: ProviderProcessSnapshot, + ): Result => { + const parsed = parser.finish(); + if (!parsed.ok) + return err( + new AnalysisOutputError( + OPERATION, + `yara stdout line ${String(parsed.error.line)} is not a documented match line: ${parsed.error.reason}.`, + { capturedOutput: capturedProviderOutput(observedSnapshot) }, + ), + ); + const diagnostics = parseYaraDiagnostics( + observedSnapshot.stderr.text, + staged.target.snapshotPath, + ruleSnapshotPaths(staged), + ); + return ok({ + parsed: parsed.value, + warnings: [...diagnostics.warnings, ...diagnostics.unrecognized].map( + (line) => restoreCallerPaths(line, staged), + ), + }); + }; + let snapshot: ProviderProcessSnapshot; + try { + // Ownership preparation has its own deadline; it does not spend yara's. + await prepareOwnedCommand(signal); + snapshot = await runOwnedCommand( + { + command, + arguments: yaraArguments(staged), + // See RULE_NAMESPACE: no relative path resolves to a rule file. + cwd: pathApi.parse(staged.target.snapshotPath).root, + runId: `rea-yara-${randomUUID()}`, + hostEnvironment: { + ...snapshotEnvironment(this.options.environment, platform), + LC_ALL: "C", + LANG: "C", + }, + }, + { + timeoutMs: settings.command_timeout_ms.value, + diagnosticBytes: maxOutputBytes, + stdout: yaraMatchOutputSink(parser), + maxStdoutBytes: maxOutputBytes, + observeCompleted: (observed) => { + completed = finalize(observed); + if (completed.ok) onCompleted?.(completed.value); + }, + }, + { + ...(signal === undefined ? {} : { signal }), + ...(this.options.launcher === undefined + ? {} + : { launcher: this.options.launcher }), + }, + ); + } catch (cause: unknown) { + if (completed !== undefined && !completed.ok) { + let failure = retainProcessInspectionCleanup( + cause, + completed.error, + scanResources, + OPERATION, + ); + const cancellation = + cause instanceof OwnedCommandFailure && + cause.cancellation !== undefined + ? cancelledBy(OPERATION, carriedReason(cause.cancellation.reason)) + : signal?.aborted + ? cancelledBy(OPERATION, signal) + : undefined; + if (cancellation !== undefined) + failure = analysisErrorWithCancellation(failure, cancellation); + if ( + cause instanceof OwnedCommandFailure && + cause.reason === "timeout" + ) { + const outcome = providerOutcomeOf(cause); + if (outcome !== undefined) + primaryAnalysisError(failure).retainSecondaryFailure( + classifyProviderOutcome(outcome, context), + ); + } + throw failure; + } + throw yaraCommandFailure(cause, context, scanResources); + } + const result = completed ?? finalize(snapshot); + if (!result.ok) throw result.error; + return result.value; + } + + #failure( + cause: unknown, + input: InspectYaraMatchesInput, + phase: ReadPhase | undefined, + maxFileBytes: number, + completedFiles: CompletedAdmittedFiles, + ) { + const read = phase ?? { + path: input.path, + field: "path", + description: "file", + }; + const facts = artifactFilePrimaryFacts(cause); + const primary = classifyProviderFailure( + facts.cause, + offlineArtifactFailureDialect(facts, { + providerId: PROVIDER_ID, + operation: OPERATION, + path: read.path, + description: read.description, + field: read.field, + fileSize: (failure) => + parseLimitConstraint( + OPERATION, + "file-size", + decodeLimit( + YARA_SCAN_FORMAT, + failure.message, + { name: "max_file_bytes", maximum: maxFileBytes }, + { cause: failure }, + ), + { + path: read.path, + retryable: false, + limit: yaraFileBytesLimit( + maxFileBytes, + failure.observedBytes !== undefined && + failure.observedBytes <= BigInt(Number.MAX_SAFE_INTEGER) + ? Number(failure.observedBytes) + : undefined, + ), + }, + ), + }), + ); + if ( + cause instanceof ArtifactReaderFailure && + cause.partialObservation !== undefined + ) + primary.retainPartialObservation(cause.partialObservation); + // `primary` already names the failing `read.path`. Once the scanned target + // file is hashed, attribute `partialObservation` to it; if failure happened + // after hashing a rule file before target staging, attribute it only to + // that failing rule file. Keep all other completed admitted rule identities + // separately as `argumentObservations` so earlier rules survive later failures. + const failingRuleIndex = + Array.isArray(read.field) && + read.field[0] === "rule_paths" && + typeof read.field[1] === "number" + ? read.field[1] + : undefined; + const primaryFileIdentity = + completedFiles.target ?? + (failingRuleIndex === undefined + ? undefined + : completedFiles.rules.get(failingRuleIndex)); + const projected = projectStableArtifactFailure( + cause, + primary, + primaryFileIdentity === undefined ? read.path : primaryFileIdentity.path, + PROVIDER_ID, + OPERATION, + primaryFileIdentity, + ); + const hasCompleteReport = + projected.partialObservation !== undefined && + "matches" in projected.partialObservation; + if (!hasCompleteReport && completedFiles.rules.size > 0) { + const rootPrimary = primaryAnalysisError(projected); + for (const [index, identity] of completedFiles.rules.entries()) { + if (completedFiles.target === undefined && failingRuleIndex === index) + continue; + const observation = completedStableArtifactObservation( + undefined, + identity.path, + identity, + ); + if (observation === undefined) continue; + const argument = `rule_paths[${String(index)}]`; + projected.retainArgumentObservation(argument, observation); + if (rootPrimary !== projected) + rootPrimary.retainArgumentObservation(argument, observation); + } + } + return projected; + } +} diff --git a/src/yara/YaraOutput.test.ts b/src/yara/YaraOutput.test.ts new file mode 100644 index 00000000000..88083157abf --- /dev/null +++ b/src/yara/YaraOutput.test.ts @@ -0,0 +1,376 @@ +import { describe, expect, it } from "vitest"; + +import { + parseYaraDiagnostics, + parseYaraMeta, + YaraMatchOutputParser, +} from "./YaraOutput.js"; + +const SCANNED = "/work/sample [1].bin"; + +const parse = (text: string | Buffer, maxListed = 100, chunk = 0) => { + const parser = new YaraMatchOutputParser(SCANNED, maxListed); + const bytes = typeof text === "string" ? Buffer.from(text, "latin1") : text; + if (chunk === 0) parser.push(bytes); + else + for (let offset = 0; offset < bytes.length; offset += chunk) + parser.push(bytes.subarray(offset, offset + chunk)); + return parser.finish(); +}; + +// Recorded from yara 4.6.0 `-s -L -m -g -q` on a synthetic sample. +const RECORDED = [ + `Hello [tagA,tagB] [author="A \\"q\\" \\\\ b, c] [d",score =42,neg =-7,ok=true,nope=false,uni="caf\\303\\251"] ${SCANNED}`, + "0x4:5:$t: hello", + "0x36:5:$t: hello", + "0x0:4:$h: 4D 5A 90 00", + '0x12:26:$x: secret_KEY "quoted" \\back\\x0A', + "0x31:10:$r: tail hello", + `NoTagsNoMeta [] [] ${SCANNED}`, + "0x2c:4:$a: AAAA", + `Cond [] [] ${SCANNED}`, + "", +].join("\n"); + +describe("YaraMatchOutputParser", () => { + it("reads rules, tags, typed meta and string matches", () => { + const parsed = parse(RECORDED); + expect(parsed.ok).toBe(true); + if (!parsed.ok) return; + expect(parsed.value.stringMatches).toBe(6); + expect(parsed.value.listedStringMatches).toBe(6); + expect(parsed.value.matches).toEqual([ + { + rule: "Hello", + tags: ["tagA", "tagB"], + meta: [ + { identifier: "author", type: "string", value: 'A "q" \\ b, c] [d' }, + { identifier: "score", type: "integer", value: 42 }, + { identifier: "neg", type: "integer", value: -7 }, + { identifier: "ok", type: "boolean", value: true }, + { identifier: "nope", type: "boolean", value: false }, + { identifier: "uni", type: "string", value: "café" }, + ], + string_match_count: 5, + strings: [ + { identifier: "$t", file_offset: 4, length: 5, data: "hello" }, + { identifier: "$t", file_offset: 0x36, length: 5, data: "hello" }, + { + identifier: "$h", + file_offset: 0, + length: 4, + data: "4D 5A 90 00", + }, + { + identifier: "$x", + file_offset: 0x12, + length: 26, + data: 'secret_KEY "quoted" \\back\\x0A', + }, + { + identifier: "$r", + file_offset: 0x31, + length: 10, + data: "tail hello", + }, + ], + }, + { + rule: "NoTagsNoMeta", + tags: [], + meta: [], + string_match_count: 1, + strings: [ + { identifier: "$a", file_offset: 0x2c, length: 4, data: "AAAA" }, + ], + }, + { rule: "Cond", tags: [], meta: [], string_match_count: 0, strings: [] }, + ]); + }); + + it("parses identically when stdout arrives one byte at a time", () => { + expect(parse(RECORDED, 100, 1)).toEqual(parse(RECORDED)); + }); + + it("accepts CRLF line ends", () => { + expect(parse(RECORDED.replaceAll("\n", "\r\n"))).toEqual(parse(RECORDED)); + }); + + it("counts matches beyond the listing budget without retaining them", () => { + const parsed = parse(RECORDED, 2); + expect(parsed.ok).toBe(true); + if (!parsed.ok) return; + expect(parsed.value.stringMatches).toBe(6); + expect(parsed.value.listedStringMatches).toBe(2); + expect(parsed.value.matches.map((match) => match.strings.length)).toEqual([ + 2, 0, 0, + ]); + expect( + parsed.value.matches.map((match) => match.string_match_count), + ).toEqual([5, 1, 0]); + }); + + it("reports empty output as no matches", () => { + expect(parse("")).toEqual({ + ok: true, + value: { matches: [], stringMatches: 0, listedStringMatches: 0 }, + }); + }); + + it("refuses output that ends inside a line", () => { + expect(parse(RECORDED.slice(0, -1))).toEqual({ + ok: false, + error: { line: 9, reason: "stdout ended inside a line" }, + }); + }); + + it("refuses a rule line for another file", () => { + expect(parse("Other [] [] /work/other.bin\n")).toEqual({ + ok: false, + error: { line: 1, reason: "rule line does not name the scanned file" }, + }); + }); + + it("refuses a string line before any rule", () => { + expect(parse("0x0:1:$a: A\n")).toEqual({ + ok: false, + error: { line: 1, reason: "string match line before any rule line" }, + }); + }); + + it("refuses malformed string lines", () => { + const parsed = parse(`R [] [] ${SCANNED}\n0xZZ:1:$a: A\n`); + expect(parsed).toEqual({ + ok: false, + error: { line: 2, reason: "malformed string match line" }, + }); + }); + + it("refuses offsets beyond the safe integer range", () => { + const parsed = parse(`R [] [] ${SCANNED}\n0x20000000000000:1:$a: A\n`); + expect(parsed).toEqual({ + ok: false, + error: { + line: 2, + reason: "string match offset or length exceeds the safe range", + }, + }); + }); + + it("keeps a matched data field that itself contains a line prefix", () => { + const parsed = parse(`R [] [] ${SCANNED}\n0x0:6:$a: 0x0:1:\n`); + expect(parsed.ok && parsed.value.matches[0]?.strings[0]?.data).toBe( + "0x0:1:", + ); + }); +}); + +describe("parseYaraMeta", () => { + it("decodes escapes and octal bytes", () => { + expect(parseYaraMeta('a="x\\ny\\tz\\r\\101"')).toEqual([ + { identifier: "a", type: "string", value: "x\ny\tz\rA" }, + ]); + }); + + it("decodes every escape yara's print_escaped_data writes", () => { + // Quote, apostrophe and backslash are backslash-escaped; 0x07..0x0d use + // C escapes; other control and high bytes are three-digit octal. + expect( + parseYaraMeta(String.raw`a="it\'s \"q\" \\ \a\b\t\n\v\f\r\033\177"`), + ).toEqual([ + { + identifier: "a", + type: "string", + value: 'it\'s "q" \\ \x07\x08\t\n\x0b\x0c\r\x1b\x7f', + }, + ]); + }); + + it("refuses an octal escape yara does not write", () => { + expect(parseYaraMeta(String.raw`a="\1"`)).toBe( + "unknown escape \\1 in a meta string", + ); + expect(parseYaraMeta(String.raw`a="\400"`)).toBe( + "unknown escape \\4 in a meta string", + ); + }); + + it("keeps non UTF-8 strings as hex bytes", () => { + expect(parseYaraMeta('a="\\377\\376"')).toEqual([ + { identifier: "a", type: "bytes", value: "fffe" }, + ]); + }); + + it("keeps integers beyond the safe range as decimal text", () => { + expect(parseYaraMeta("big =9223372036854775807")).toEqual([ + { identifier: "big", type: "integer", value: "9223372036854775807" }, + ]); + }); + + it("returns a reason for malformed entries", () => { + expect(parseYaraMeta('a="open')).toBe("unterminated meta string"); + expect(parseYaraMeta("a=maybe")).toBe('invalid meta value "maybe"'); + expect(parseYaraMeta('a="\\q"')).toBe( + "unknown escape \\q in a meta string", + ); + expect(parseYaraMeta("noValue")).toBe("meta entry without a value"); + }); +}); + +describe("parseYaraDiagnostics", () => { + it("classifies recorded yara stderr forms", () => { + expect( + parseYaraDiagnostics( + [ + 'warning: rule "Slow" in /r/m.yar(2): string "$a" may slow down scanning', + "/r/m.yar(4): warning: rule-less warning", + 'error: rule "Bad" in /r/bad.yar(1): undefined identifier "nope"', + '/r/a2.yar(1): error: duplicated identifier "A"', + "/rules/main.yar(1): error: can't open include file: /rules/common.yar", + "/r/s.yar(7): error: syntax error, unexpected ", + '/r/u.yar(2): error: unknown module "nope"', + "/r/c.yar(3): error: include circular reference", + 'error: rule "R" in /r/o.yar(5): "pe" is not a structure', + "error: could not open file: /r/missing.yar", + `error scanning ${SCANNED}: could not open file`, + "something else", + "", + ].join("\n"), + SCANNED, + ), + ).toEqual({ + warnings: [ + 'warning: rule "Slow" in /r/m.yar(2): string "$a" may slow down scanning', + "/r/m.yar(4): warning: rule-less warning", + ], + compileErrors: [ + { + kind: "undefined", + source: "/r/bad.yar", + line: 1, + rule: "Bad", + message: 'undefined identifier "nope"', + }, + { + kind: "duplicate", + source: "/r/a2.yar", + line: 1, + rule: null, + message: 'duplicated identifier "A"', + }, + { + kind: "include", + source: "/rules/main.yar", + line: 1, + rule: null, + message: "can't open include file: /rules/common.yar", + }, + { + kind: "syntax", + source: "/r/s.yar", + line: 7, + rule: null, + message: "syntax error, unexpected ", + }, + { + kind: "undefined", + source: "/r/u.yar", + line: 2, + rule: null, + message: 'unknown module "nope"', + }, + { + kind: "include", + source: "/r/c.yar", + line: 3, + rule: null, + message: "include circular reference", + }, + { + kind: "other", + source: "/r/o.yar", + line: 5, + rule: "R", + message: '"pe" is not a structure', + }, + { + kind: "unreadable_file", + source: "/r/missing.yar", + line: null, + rule: null, + message: "could not open file", + }, + ], + scanErrors: [{ path: SCANNED, reason: "could not open file" }], + unrecognized: ["something else"], + }); + }); + + it("matches a FILE yara was given exactly and splits any other FILE only where one complete diagnostic remains", () => { + const odd = "/r/odd(2): x.yar"; + expect( + parseYaraDiagnostics( + [ + `${odd}(4): error: syntax error, unexpected "(9): error: "`, + '/inc/a.yar(3): error: undefined identifier "b(1): c"', + `error: rule "S" in ${odd}(6): undefined string "$x"`, + // An included file whose name contains "(N): ". + "/rules/odd(2): x.yar(4): error: syntax error", + // Two splits each leave a complete diagnostic: the location is unknown. + 'error: rule "T" in /rules/odd(2): x.yar(7): undefined identifier "q"', + "/a(1): error: b.yar(2): error: syntax error", + ].join("\n"), + SCANNED, + [odd], + ), + ).toEqual({ + warnings: [], + compileErrors: [ + { + kind: "syntax", + source: odd, + line: 4, + rule: null, + message: 'syntax error, unexpected "(9): error: "', + }, + { + kind: "undefined", + source: "/inc/a.yar", + line: 3, + rule: null, + message: 'undefined identifier "b(1): c"', + }, + { + kind: "undefined", + source: odd, + line: 6, + rule: "S", + message: 'undefined string "$x"', + }, + { + kind: "syntax", + source: "/rules/odd(2): x.yar", + line: 4, + rule: null, + message: "syntax error", + }, + { + kind: "other", + source: null, + line: null, + rule: "T", + message: '/rules/odd(2): x.yar(7): undefined identifier "q"', + }, + { + kind: "other", + source: null, + line: null, + rule: null, + message: "/a(1): error: b.yar(2): error: syntax error", + }, + ], + scanErrors: [], + unrecognized: [], + }); + }); +}); diff --git a/src/yara/YaraOutput.ts b/src/yara/YaraOutput.ts new file mode 100644 index 00000000000..1ac69527c43 --- /dev/null +++ b/src/yara/YaraOutput.ts @@ -0,0 +1,476 @@ +import { Writable } from "node:stream"; + +import { Budget } from "../domain/budget.js"; +import { decodeStrictUtf8, isStrictUtf8 } from "../domain/strictUtf8.js"; +import { err, ok, type Result } from "../domain/result.js"; +import type { + YaraMeta, + YaraRuleMatch, + YaraStringMatch, +} from "../domain/yara/yaraMatches.js"; + +/** Output of `yara -s -L -m -g` for one scanned file, read once here. */ +export interface YaraParsedMatches { + readonly matches: readonly YaraRuleMatch[]; + /** Every string match yara reported, listed or not. */ + readonly stringMatches: number; + readonly listedStringMatches: number; +} + +/** Where yara stdout stopped matching its documented line grammar. */ +export interface YaraOutputFailure { + /** One-based stdout line number. */ + readonly line: number; + readonly reason: string; +} + +const NEWLINE = 0x0a; +const RULE_PREFIX = + /^([A-Za-z_][A-Za-z0-9_]*) \[([A-Za-z0-9_,]*)\] \[(.*)\]$/su; +const STRING_LINE = /^0x([0-9a-f]+):(\d+):(\$[A-Za-z0-9_]*): (.*)$/su; +const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/u; +const DECIMAL = /^-?\d+$/u; + +const safeInteger = (text: string, radix: 10 | 16): number | undefined => { + const value = BigInt(radix === 16 ? `0x${text}` : text); + return value <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(value) : undefined; +}; + +/** + * The escapes yara 4.x `cli/yara.c` `print_escaped_data` writes for a string + * meta value (unchanged from v4.2.0 to v4.6.0): a backslash before a double + * quote, a single quote or a backslash; the C escapes a, b, t, n, v, f and r + * for bytes 0x07 to 0x0d; and a backslash with exactly three octal digits for + * every other byte below 0x20 or at or above 0x7f. + */ +const META_ESCAPES: Readonly> = { + '"': 0x22, + "'": 0x27, + "\\": 0x5c, + a: 0x07, + b: 0x08, + t: 0x09, + n: 0x0a, + v: 0x0b, + f: 0x0c, + r: 0x0d, +}; +const META_OCTAL_ESCAPE = /^[0-3][0-7]{2}/u; + +/** Decode one quoted meta string as yara escapes it. */ +const decodeMetaString = ( + text: string, + start: number, +): { readonly bytes: Buffer; readonly end: number } | string => { + const bytes: number[] = []; + let index = start; + while (index < text.length) { + const char = text[index]!; + if (char === '"') return { bytes: Buffer.from(bytes), end: index + 1 }; + if (char !== "\\") { + bytes.push(char.charCodeAt(0)); + index += 1; + continue; + } + const next = text[index + 1]; + const simple = next === undefined ? undefined : META_ESCAPES[next]; + if (simple !== undefined) { + bytes.push(simple); + index += 2; + continue; + } + const octal = META_OCTAL_ESCAPE.exec(text.slice(index + 1, index + 4))?.[0]; + if (octal === undefined) + return `unknown escape \\${next ?? ""} in a meta string`; + bytes.push(Number.parseInt(octal, 8)); + index += 1 + octal.length; + } + return "unterminated meta string"; +}; + +const metaValue = (identifier: string, bytes: Buffer): YaraMeta => + isStrictUtf8(bytes) + ? { + identifier, + type: "string", + value: decodeStrictUtf8(bytes, "preserve"), + } + : { identifier, type: "bytes", value: bytes.toString("hex") }; + +/** Parse the bracketed meta list of one rule line. */ +export const parseYaraMeta = (text: string): YaraMeta[] | string => { + const meta: YaraMeta[] = []; + let index = 0; + while (index < text.length) { + // yara prints integer meta as `name =value` and the others as `name=value`. + const equals = text.indexOf("=", index); + if (equals === -1) return "meta entry without a value"; + const identifier = text.slice(index, equals).trimEnd(); + if (!IDENTIFIER.test(identifier)) + return `invalid meta identifier ${JSON.stringify(identifier)}`; + let cursor = equals + 1; + if (text[cursor] === '"') { + const decoded = decodeMetaString(text, cursor + 1); + if (typeof decoded === "string") return decoded; + meta.push(metaValue(identifier, decoded.bytes)); + cursor = decoded.end; + } else { + const comma = text.indexOf(",", cursor); + const token = text.slice(cursor, comma === -1 ? text.length : comma); + if (token === "true" || token === "false") + meta.push({ identifier, type: "boolean", value: token === "true" }); + else if (DECIMAL.test(token)) { + const magnitude = safeInteger(token.replace(/^-/u, ""), 10); + meta.push({ + identifier, + type: "integer", + value: + magnitude === undefined + ? token + : token.startsWith("-") + ? -magnitude + : magnitude, + }); + } else return `invalid meta value ${JSON.stringify(token)}`; + cursor += token.length; + } + if (cursor === text.length) break; + if (text[cursor] !== ",") return "meta entries are not comma separated"; + index = cursor + 1; + } + return meta; +}; + +interface OpenRule { + readonly rule: string; + readonly tags: string[]; + readonly meta: YaraMeta[]; + readonly strings: YaraStringMatch[]; + stringMatchCount: number; +} + +/** + * Incremental parser of one scan's stdout. Rule lines end with the scanned + * path exactly as it was passed to yara, which keeps paths containing spaces + * or brackets unambiguous. String matches beyond `maxListed` are counted but + * not retained. + */ +export class YaraMatchOutputParser { + readonly #suffix: Buffer; + readonly #listing: Budget; + readonly #pending: Buffer[] = []; + readonly #matches: YaraRuleMatch[] = []; + #open: OpenRule | undefined; + #line = 0; + #stringMatches = 0; + #failure: YaraOutputFailure | undefined; + + constructor(scannedPath: string, maxListed: number) { + this.#suffix = Buffer.from(` ${scannedPath}`, "utf8"); + this.#listing = new Budget(maxListed); + } + + /** Accept one stdout chunk; a grammar failure is kept, never thrown. */ + push(chunk: Buffer): void { + if (this.#failure !== undefined) return; + let start = 0; + for ( + let newline = chunk.indexOf(NEWLINE, start); + newline !== -1; + newline = chunk.indexOf(NEWLINE, start) + ) { + this.#pending.push(chunk.subarray(start, newline)); + const line = Buffer.concat(this.#pending); + this.#pending.length = 0; + start = newline + 1; + this.#parseLine(line); + if (this.#failure !== undefined) return; + } + if (start < chunk.length) + this.#pending.push(Buffer.from(chunk.subarray(start))); + } + + /** The parsed matches once stdout has ended. */ + finish(): Result { + if (this.#failure !== undefined) return err(this.#failure); + if (this.#pending.some((part) => part.length > 0)) + return err({ + line: this.#line + 1, + reason: "stdout ended inside a line", + }); + this.#close(); + return ok({ + matches: this.#matches, + stringMatches: this.#stringMatches, + listedStringMatches: this.#listing.used, + }); + } + + #parseLine(raw: Buffer): void { + this.#line += 1; + // yara on Windows writes CRLF line ends. + const line = raw.at(-1) === 0x0d ? raw.subarray(0, -1) : raw; + const fail = (reason: string) => { + this.#failure = { line: this.#line, reason }; + }; + if (line.subarray(0, 2).toString("latin1") === "0x") { + const parsed = STRING_LINE.exec(line.toString("latin1")); + if (parsed === null) return fail("malformed string match line"); + if (this.#open === undefined) + return fail("string match line before any rule line"); + const offset = safeInteger(parsed[1]!, 16); + const length = safeInteger(parsed[2]!, 10); + if (offset === undefined || length === undefined) + return fail("string match offset or length exceeds the safe range"); + this.#open.stringMatchCount += 1; + this.#stringMatches += 1; + if (this.#listing.tryCharge(1)) + this.#open.strings.push({ + identifier: parsed[3]!, + file_offset: offset, + length, + data: parsed[4]!, + }); + return; + } + if ( + line.length <= this.#suffix.length || + !line.subarray(line.length - this.#suffix.length).equals(this.#suffix) + ) + return fail("rule line does not name the scanned file"); + const prefix = line + .subarray(0, line.length - this.#suffix.length) + .toString("latin1"); + const parsed = RULE_PREFIX.exec(prefix); + if (parsed === null) return fail("malformed rule line"); + const meta = parseYaraMeta(parsed[3]!); + if (typeof meta === "string") return fail(meta); + this.#close(); + this.#open = { + rule: parsed[1]!, + tags: parsed[2] === "" ? [] : parsed[2]!.split(","), + meta, + strings: [], + stringMatchCount: 0, + }; + } + + #close(): void { + if (this.#open === undefined) return; + const { rule, tags, meta, strings, stringMatchCount } = this.#open; + this.#matches.push({ + rule, + tags, + meta, + string_match_count: stringMatchCount, + strings, + }); + this.#open = undefined; + } +} + +/** A stdout sink that feeds one parser and never rejects a write. */ +export const yaraMatchOutputSink = (parser: YaraMatchOutputParser): Writable => + new Writable({ + write(chunk: Buffer, _encoding, callback) { + parser.push(chunk); + callback(); + }, + }); + +/** + * What a rule compile error means for the caller's repair. The kinds follow + * libyara 4.x message text (`yr_compiler_get_error_message` and the lexer's + * include errors); any other message is `other` and keeps its text. + */ +export type YaraCompileErrorKind = + | "include" + | "syntax" + | "undefined" + | "duplicate" + | "unreadable_file" + | "other"; + +/** One rule compile error; `source` is the file yara named, which may be an included file. */ +export interface YaraCompileError { + readonly kind: YaraCompileErrorKind; + /** + * The file yara named, or `null` with `line: null` when the text cannot be + * split into a file and line unambiguously; `message` then keeps it whole. + */ + readonly source: string | null; + readonly line: number | null; + /** The rule yara named, when the error belongs to one. */ + readonly rule: string | null; + readonly message: string; +} + +/** Every diagnostic yara wrote to stderr, read once here. */ +export interface YaraDiagnostics { + readonly warnings: readonly string[]; + readonly compileErrors: readonly YaraCompileError[]; + readonly scanErrors: readonly { + readonly path: string; + readonly reason: string; + }[]; + /** Lines that match none of the documented forms, kept verbatim. */ + readonly unrecognized: readonly string[]; +} + +// yara 4.x cli/yara.c print_compiler_error writes exactly two forms: +// LEVEL: rule "RULE" in FILE(LINE): MESSAGE (the error belongs to a rule) +// FILE(LINE): LEVEL: MESSAGE (it does not, e.g. includes) +// cli/common.c writes `error: could not open file: FILE` for a rule file it +// cannot open. FILE is the path passed to yara, after any NAMESPACE: prefix. +// A file name and a message can both contain `(N): `. A FILE yara was given +// is matched exactly. Any other FILE, such as an included file, is split at +// every `(N): ` that leaves a complete diagnostic; one such split is the +// location, and several leave the location unknown. +const RULE_DIAGNOSTIC_PREFIX = /^(error|warning): rule "([^"]*)" in /u; +const LEVELS = ["error", "warning"] as const; +type YaraLevel = (typeof LEVELS)[number]; +const LOCATION = /\((\d+)\): /gu; +const OPEN_ERROR = /^error: could not open file: (.+)$/u; +const BARE_WARNING = /^warning: .+$/u; + +interface Located { + readonly source: string; + readonly line: number; + readonly rest: string; +} + +/** Every `FILE(LINE): REST` split of `text`; a FILE yara was given wins. */ +const locations = ( + text: string, + sources: readonly string[], +): readonly Located[] => { + const all: Located[] = []; + for (const match of text.matchAll(LOCATION)) { + if (match.index === 0) continue; + all.push({ + source: text.slice(0, match.index), + line: Number(match[1]), + rest: text.slice(match.index + match[0].length), + }); + } + const given = all.filter((candidate) => sources.includes(candidate.source)); + return given.length > 0 ? given.slice(0, 1) : all; +}; + +const INCLUDE_MESSAGE = + /^(?:can't open include file: |callback failed to provide include resource: |includes? circular reference$|too many levels of included rules$|includes depth exceeded$|includes are disabled$)/u; + +/** Classify one compiler message by the libyara text that produced it. */ +export const yaraCompileErrorKind = (message: string): YaraCompileErrorKind => + INCLUDE_MESSAGE.test(message) + ? "include" + : message.startsWith("syntax error") + ? "syntax" + : /^(?:undefined (?:identifier|string) |unknown module )/u.test(message) + ? "undefined" + : message.startsWith("duplicated ") + ? "duplicate" + : "other"; + +/** + * Classify yara stderr by line; scan errors must name the scanned path. + * `ruleSources` are the rule file paths yara was given, matched exactly. + */ +export const parseYaraDiagnostics = ( + stderr: string, + scannedPath: string, + ruleSources: readonly string[] = [], +): YaraDiagnostics => { + const scanError = `error scanning ${scannedPath}: `; + const warnings: string[] = []; + const compileErrors: YaraCompileError[] = []; + const scanErrors: YaraDiagnostics["scanErrors"][number][] = []; + const unrecognized: string[] = []; + const record = ( + level: YaraLevel, + rule: string | null, + candidates: readonly { + readonly located: Located; + readonly message: string; + }[], + whole: string, + raw: string, + ): void => { + if (level === "warning") { + warnings.push(raw); + return; + } + const only = candidates.length === 1 ? candidates[0] : undefined; + const kinds = new Set( + candidates.map(({ message }) => yaraCompileErrorKind(message)), + ); + compileErrors.push( + only === undefined + ? { + kind: kinds.size === 1 ? [...kinds][0]! : "other", + source: null, + line: null, + rule, + message: whole, + } + : { + kind: yaraCompileErrorKind(only.message), + source: only.located.source, + line: only.located.line, + rule, + message: only.message, + }, + ); + }; + const parse = (line: string): boolean => { + const ruled = RULE_DIAGNOSTIC_PREFIX.exec(line); + if (ruled !== null) { + const text = line.slice(ruled[0].length); + const candidates = locations(text, ruleSources) + .filter(({ rest }) => rest !== "") + .map((located) => ({ located, message: located.rest })); + if (candidates.length === 0) return false; + record(ruled[1] as YaraLevel, ruled[2]!, candidates, text, line); + return true; + } + const candidates = locations(line, ruleSources).flatMap((located) => { + const level = LEVELS.find((candidate) => + located.rest.startsWith(`${candidate}: `), + ); + const message = + level === undefined ? "" : located.rest.slice(level.length + 2); + return level === undefined || message === "" + ? [] + : [{ located, level, message }]; + }); + if (candidates.length === 0) return false; + // A split that reads as an error keeps the line a compile error. + const level = candidates.some(({ level }) => level === "error") + ? "error" + : "warning"; + record(level, null, candidates, line, line); + return true; + }; + for (const raw of stderr.split("\n")) { + const line = raw.endsWith("\r") ? raw.slice(0, -1) : raw; + if (line.trim() === "") continue; + let match: RegExpExecArray | null; + if (line.startsWith(scanError) && line.length > scanError.length) + scanErrors.push({ + path: scannedPath, + reason: line.slice(scanError.length), + }); + else if (parse(line)) continue; + else if ((match = OPEN_ERROR.exec(line)) !== null) + compileErrors.push({ + kind: "unreadable_file", + source: match[1]!, + line: null, + rule: null, + message: "could not open file", + }); + else if (BARE_WARNING.test(line)) warnings.push(line); + else unrecognized.push(line); + } + return { warnings, compileErrors, scanErrors, unrecognized }; +}; diff --git a/src/yara/YaraProviderIdentity.ts b/src/yara/YaraProviderIdentity.ts new file mode 100644 index 00000000000..5bdd47903f8 --- /dev/null +++ b/src/yara/YaraProviderIdentity.ts @@ -0,0 +1,13 @@ +/** Caller-selected yara command; its implementation and version are not observed. */ +export const YARA_PROVIDER_IDENTITY = { + id: "yara.command", + name: "yara command", + version: null, +} as const; + +/** The launch setting that selects the yara executable. */ +export const YARA_COMMAND_SETTING = "REA_YARA_COMMAND"; + +/** How a caller repairs a yara command that cannot be started. */ +export const YARA_COMMAND_REMEDIATION = + "Install YARA 4.x, then make the yara command available on PATH or set REA_YARA_COMMAND to its executable. REA does not install yara or download rules. Other tools remain available."; diff --git a/src/yara/YaraRuleIncludeRewrite.test.ts b/src/yara/YaraRuleIncludeRewrite.test.ts new file mode 100644 index 00000000000..f26fea907ce --- /dev/null +++ b/src/yara/YaraRuleIncludeRewrite.test.ts @@ -0,0 +1,235 @@ +import { describe, expect, it } from "vitest"; + +import { ArtifactReaderFailure } from "../resources/index.js"; +import { createYaraIncludeRewriter } from "./YaraRuleIncludeRewrite.js"; + +const rewrite = ( + source: string | Buffer, + sourcePath: string, + platform: NodeJS.Platform = "linux", + chunkSize?: number, + maxOutputBytes?: number, +): Buffer => { + const input = + typeof source === "string" ? Buffer.from(source, "utf8") : source; + const rewriter = createYaraIncludeRewriter( + sourcePath, + platform, + maxOutputBytes, + ); + if (chunkSize === undefined) { + return Buffer.concat([rewriter.push(input), rewriter.finish()]); + } + const parts: Buffer[] = []; + for (let offset = 0; offset < input.length; offset += chunkSize) { + parts.push(rewriter.push(input.subarray(offset, offset + chunkSize))); + } + parts.push(rewriter.finish()); + return Buffer.concat(parts); +}; + +describe("createYaraIncludeRewriter", () => { + it("prefixes relative POSIX includes without collapsing parent components and keeps absolute ones", () => { + const input = [ + 'include "common.yar"', + 'include\t"sub/nested.yar"', + 'include "../shared/base.yar"', + 'include "link/../common.yar"', + 'include "/abs/other.yar"', + "rule Main { condition: true }", + ].join("\n"); + const output = rewrite(input, "/rules/packers/main.yar", "linux").toString( + "utf8", + ); + expect(output).toBe( + [ + 'include "/rules/packers/common.yar"', + 'include\t"/rules/packers/sub/nested.yar"', + 'include "/rules/packers/../shared/base.yar"', + 'include "/rules/packers/link/../common.yar"', + 'include "/abs/other.yar"', + "rule Main { condition: true }", + ].join("\n"), + ); + expect( + rewrite('include "root.yar"\n', "/main.yar", "linux").toString("utf8"), + ).toBe('include "/root.yar"\n'); + }); + + it("resolves relative Windows includes with win32 path semantics", () => { + const input = [ + 'include "common.yar"', + 'include "..\\shared\\base.yar"', + 'include "D:\\abs\\other.yar"', + ].join("\r\n"); + const output = rewrite( + input, + "C:\\rules\\packers\\main.yar", + "win32", + ).toString("utf8"); + expect(output).toBe( + [ + 'include "C:\\rules\\packers\\common.yar"', + 'include "C:\\rules\\shared\\base.yar"', + 'include "D:\\abs\\other.yar"', + ].join("\r\n"), + ); + }); + + it("skips comments, strings, and regex literals without confusing division", () => { + const input = [ + '// include "line_comment.yar"', + '/* include "block_comment.yar" */', + "rule Demo {", + " strings:", + ' $s = "include \\"in_string.yar\\""', + ' $r = /include "in_regex.yar"/', + " condition:", + ' filesize / 2 > 0 and $s matches /include "in_matches.yar"/', + "}", + 'include "real.yar"', + ].join("\n"); + const output = rewrite(input, "/rules/main.yar", "linux").toString("utf8"); + expect(output).toContain('// include "line_comment.yar"'); + expect(output).toContain('/* include "block_comment.yar" */'); + expect(output).toContain('$s = "include \\"in_string.yar\\""'); + expect(output).toContain('$r = /include "in_regex.yar"/'); + expect(output).toContain('$s matches /include "in_matches.yar"/'); + expect(output).toContain('include "/rules/real.yar"'); + expect(output.split("\n")).toHaveLength(input.split("\n").length); + }); + + it("preserves regex arguments to module functions and distinguishes division from regex literals", () => { + const input = [ + 'import "pe"', + "rule ModuleRegex {", + " condition:", + ' pe.exports(/include "common.yar"/) and', + ' pe.imports("kernel32.dll", /include "second.yar"/) and', + ' pe.exports(/* comment */ /include "after_comment.yar"/) and', + " (filesize / 2) > 0 and", + " pe.sections[0].raw_data_size / 2 > 0 and", + " filesize / 2 + 10 / 2 > 0 and", + ' not /include "after_not.yar"/', + "}", + 'include "real.yar"', + ].join("\n"); + const whole = rewrite(input, "/rules/main.yar", "linux").toString("utf8"); + const streamed = rewrite(input, "/rules/main.yar", "linux", 1).toString( + "utf8", + ); + expect(streamed).toBe(whole); + expect(whole).toContain('pe.exports(/include "common.yar"/)'); + expect(whole).toContain( + 'pe.imports("kernel32.dll", /include "second.yar"/)', + ); + expect(whole).toContain( + 'pe.exports(/* comment */ /include "after_comment.yar"/)', + ); + expect(whole).toContain("(filesize / 2) > 0"); + expect(whole).toContain("pe.sections[0].raw_data_size / 2 > 0"); + expect(whole).toContain("filesize / 2 + 10 / 2 > 0"); + expect(whole).toContain('not /include "after_not.yar"/'); + expect(whole).toContain('include "/rules/real.yar"'); + expect(whole.split("\n")).toHaveLength(input.split("\n").length); + }); + + it("only rewrites top-level include directives outside rule bodies", () => { + const input = [ + "rule Body {", + " strings:", + " $h = { 4D 5A }", + " condition:", + ' $h and pe.exports(/include "inside_rule.yar"/)', + "}", + 'include "top_level.yar"', + ].join("\n"); + const output = rewrite(input, "/rules/main.yar", "linux").toString("utf8"); + expect(output).toContain('pe.exports(/include "inside_rule.yar"/)'); + expect(output).toContain('include "/rules/top_level.yar"'); + }); + + it("produces identical output across 1-byte chunk boundaries and preserves non-UTF-8 bytes", () => { + const prefix = Buffer.from("// ", "utf8"); + const rawBytes = Buffer.from([0xff, 0xfe, 0x80]); + const rest = Buffer.from( + '\ninclude "common.yar"\nrule R { condition: true }\n', + "utf8", + ); + const input = Buffer.concat([prefix, rawBytes, rest]); + const whole = rewrite(input, "/rules/main.yar", "linux"); + const streamed = rewrite(input, "/rules/main.yar", "linux", 1); + expect(streamed.equals(whole)).toBe(true); + expect(streamed.subarray(3, 6).equals(rawBytes)).toBe(true); + expect(streamed.toString("latin1")).toContain( + 'include "/rules/common.yar"', + ); + }); + + it("preserves non-UTF-8 bytes inside relative and absolute include filenames", () => { + const rawRel = Buffer.from([ + 0x66, 0x69, 0x6c, 0x65, 0xff, 0xfe, 0x2e, 0x79, 0x61, 0x72, + ]); + const rawAbs = Buffer.from([ + 0x2f, 0x61, 0x62, 0x73, 0x2f, 0x80, 0xff, 0x2e, 0x79, 0x61, 0x72, + ]); + const input = Buffer.concat([ + Buffer.from('include "', "utf8"), + rawRel, + Buffer.from('"\ninclude "', "utf8"), + rawAbs, + Buffer.from('"\nrule R { condition: true }\n', "utf8"), + ]); + const expected = Buffer.concat([ + Buffer.from('include "/rules/', "utf8"), + rawRel, + Buffer.from('"\ninclude "', "utf8"), + rawAbs, + Buffer.from('"\nrule R { condition: true }\n', "utf8"), + ]); + const whole = rewrite(input, "/rules/main.yar", "linux"); + const streamed = rewrite(input, "/rules/main.yar", "linux", 1); + expect(whole.equals(expected)).toBe(true); + expect(streamed.equals(expected)).toBe(true); + }); + + it("stops before emitting rewritten bytes past maxOutputBytes on POSIX and Windows", () => { + const longDir = `/rules/${"nested/".repeat(20)}main.yar`; + const input = 'include "a.yar"\ninclude "b.yar"\n'; + const expected = rewrite(input, longDir, "linux"); + expect(expected.length).toBeGreaterThan(Buffer.byteLength(input)); + + expect( + rewrite(input, longDir, "linux", undefined, expected.length).equals( + expected, + ), + ).toBe(true); + expect(() => + rewrite(input, longDir, "linux", undefined, expected.length - 1), + ).toThrow(ArtifactReaderFailure); + expect(() => + rewrite(input, longDir, "linux", 1, expected.length - 1), + ).toThrow( + expect.objectContaining({ + reason: "limit", + boundary: "file-size", + }), + ); + + const winLongPath = `C:\\rules\\${"nested\\".repeat(20)}main.yar`; + const winExpected = rewrite(input, winLongPath, "win32"); + expect(winExpected.length).toBeGreaterThan(Buffer.byteLength(input)); + expect( + rewrite( + input, + winLongPath, + "win32", + undefined, + winExpected.length, + ).equals(winExpected), + ).toBe(true); + expect(() => + rewrite(input, winLongPath, "win32", undefined, winExpected.length - 1), + ).toThrow(ArtifactReaderFailure); + }); +}); diff --git a/src/yara/YaraRuleIncludeRewrite.ts b/src/yara/YaraRuleIncludeRewrite.ts new file mode 100644 index 00000000000..5184fa30e92 --- /dev/null +++ b/src/yara/YaraRuleIncludeRewrite.ts @@ -0,0 +1,341 @@ +import { posix, win32 } from "node:path"; + +import { ArtifactReaderFailure } from "../resources/index.js"; + +/** Upper bound on a single buffered `include "..."` path before passing it through verbatim. */ +const MAX_INCLUDE_PATH_BYTES = 64 * 1024; + +type LexState = + | "code" + | "slash_pending" + | "line_comment" + | "block_comment" + | "block_comment_star" + | "string" + | "string_escape" + | "regex" + | "regex_escape" + | "include_ws" + | "include_path"; + +const isIdentChar = (byte: number): boolean => + (byte >= 0x41 && byte <= 0x5a) || + (byte >= 0x61 && byte <= 0x7a) || + (byte >= 0x30 && byte <= 0x39) || + byte === 0x5f; + +const isHorizSpace = (byte: number): boolean => byte === 0x20 || byte === 0x09; + +const isWhitespace = (byte: number): boolean => + byte === 0x20 || + byte === 0x09 || + byte === 0x0a || + byte === 0x0d || + byte === 0x0c || + byte === 0x0b; + +/** + * YARA keywords that act as operators or expression prefixes, so a following + * `/` begins a regex literal rather than numeric division. + */ +const REGEX_INTRO_KEYWORDS = new Set([ + "matches", + "contains", + "icontains", + "startswith", + "istartswith", + "endswith", + "iendswith", + "iequals", + "and", + "or", + "not", + "defined", + "in", + "at", +]); + +/** Streaming byte-preserving rewriter for relative YARA `include "..."` directives. */ +export interface YaraIncludeRewriter { + push(chunk: Buffer): Buffer; + finish(): Buffer; +} + +const isAsciiLetter = (byte: number): boolean => + (byte >= 0x41 && byte <= 0x5a) || (byte >= 0x61 && byte <= 0x7a); + +const isAbsoluteIncludeBytes = ( + rawBytes: readonly number[], + platform: NodeJS.Platform, +): boolean => { + const first = rawBytes[0]; + if (first === undefined) return false; + if (platform !== "win32") return first === 0x2f; + if (first === 0x2f || first === 0x5c) return true; + return rawBytes.length >= 2 && isAsciiLetter(first) && rawBytes[1] === 0x3a; +}; + +/** + * Resolve relative `include "..."` directives in a staged YARA rule file + * against the caller-selected rule file's directory so YARA keeps the + * original include lookup when compiling from an owned temporary snapshot. + * + * Operates on raw bytes to preserve non-UTF-8 content and exact line numbers, + * and skips comments, double-quoted strings, and regex literals. + */ +export const createYaraIncludeRewriter = ( + sourcePath: string, + platform: NodeJS.Platform, + maxOutputBytes?: number, +): YaraIncludeRewriter => { + const pathApi = platform === "win32" ? win32 : posix; + const baseDir = pathApi.dirname(sourcePath); + const baseDirPrefix = + platform === "win32" + ? /[\\/]$/u.test(baseDir) + ? baseDir + : `${baseDir}\\` + : baseDir.endsWith("/") + ? baseDir + : `${baseDir}/`; + // YARA's `[^\"]+` lexer rule ends at the first quote and cannot + // represent line breaks; pass through verbatim if unrepresentable. + const baseDirPrefixBytes = + baseDirPrefix.includes('"') || /[\r\n]/u.test(baseDirPrefix) + ? null + : Buffer.from(baseDirPrefix, "utf8"); + + let state: LexState = "code"; + let ident = ""; + let identOverflow = false; + let braceDepth = 0; + let canStartRegex = true; + let includePathBytes: number[] = []; + let emittedBytes = 0; + + const reserveBytes = (count: number): void => { + const next = emittedBytes + count; + if (maxOutputBytes !== undefined && next > maxOutputBytes) + throw new ArtifactReaderFailure( + "limit", + `Staged rule file exceeds max_file_bytes (${String(maxOutputBytes)} bytes) after rewriting relative includes: ${sourcePath}`, + { boundary: "file-size" }, + ); + emittedBytes = next; + }; + + return { + push(chunk: Buffer): Buffer { + const out: number[] = []; + const emit = (byte: number): void => { + reserveBytes(1); + out.push(byte); + }; + const emitBuffer = (bytes: Uint8Array | readonly number[]): void => { + if (bytes.length === 0) return; + reserveBytes(bytes.length); + for (const byte of bytes) out.push(byte); + }; + const emitPrefixed = ( + prefix: Uint8Array, + rawBytes: readonly number[], + ): void => { + reserveBytes(prefix.length + rawBytes.length); + for (const byte of prefix) out.push(byte); + for (const byte of rawBytes) out.push(byte); + }; + const emitRewrittenPath = (rawBytes: readonly number[]): void => { + if ( + rawBytes.length === 0 || + isAbsoluteIncludeBytes(rawBytes, platform) + ) { + emitBuffer(rawBytes); + return; + } + if (platform !== "win32") { + // Preserve raw filename bytes and POSIX `link/..` components by prefixing + // the rule file's parent directory directly without lexical normalization. + if (baseDirPrefixBytes === null) { + emitBuffer(rawBytes); + return; + } + emitPrefixed(baseDirPrefixBytes, rawBytes); + return; + } + const rawBuffer = Buffer.from(rawBytes); + const raw = rawBuffer.toString("utf8"); + if (Buffer.from(raw, "utf8").equals(rawBuffer)) { + const resolved = win32.resolve(baseDir, raw); + if (resolved.includes('"') || /[\r\n]/u.test(resolved)) { + emitBuffer(rawBytes); + return; + } + const resolvedLength = Buffer.byteLength(resolved, "utf8"); + reserveBytes(resolvedLength); + const resolvedBytes = Buffer.from(resolved, "utf8"); + for (const byte of resolvedBytes) out.push(byte); + return; + } + if (baseDirPrefixBytes === null) { + emitBuffer(rawBytes); + return; + } + emitPrefixed(baseDirPrefixBytes, rawBytes); + }; + + const processCodeByte = (byte: number): void => { + if (ident.length > 0 && !isIdentChar(byte)) { + const word = identOverflow ? "" : ident; + ident = ""; + identOverflow = false; + if (braceDepth === 0 && word === "include" && isHorizSpace(byte)) { + emit(byte); + canStartRegex = false; + state = "include_ws"; + return; + } + canStartRegex = REGEX_INTRO_KEYWORDS.has(word); + } + if (isIdentChar(byte)) { + emit(byte); + if (!identOverflow) { + if (ident.length < 16) ident += String.fromCharCode(byte); + else identOverflow = true; + } + return; + } + if (byte === 0x2f) { + emit(byte); + state = "slash_pending"; + return; + } + if (byte === 0x22) { + emit(byte); + canStartRegex = false; + state = "string"; + return; + } + if (byte === 0x7b) { + braceDepth += 1; + canStartRegex = true; + emit(byte); + return; + } + if (byte === 0x7d) { + if (braceDepth > 0) braceDepth -= 1; + canStartRegex = true; + emit(byte); + return; + } + emit(byte); + if (!isWhitespace(byte)) { + // `)` (0x29) and `]` (0x5d) end a value expression, so a following + // `/` is numeric division; other punctuation (such as `(`, `,`, `=`, + // operators) can precede a regex literal. + canStartRegex = byte !== 0x29 && byte !== 0x5d; + } + }; + + for (const byte of chunk) { + switch (state) { + case "code": + processCodeByte(byte); + break; + case "slash_pending": + if (byte === 0x2f) { + emit(byte); + state = "line_comment"; + } else if (byte === 0x2a) { + emit(byte); + state = "block_comment"; + } else if (canStartRegex) { + canStartRegex = false; + emit(byte); + if (byte === 0x5c) state = "regex_escape"; + else if (byte === 0x0a) state = "code"; + else state = "regex"; + } else { + canStartRegex = true; + state = "code"; + processCodeByte(byte); + } + break; + case "line_comment": + emit(byte); + if (byte === 0x0a) state = "code"; + break; + case "block_comment": + emit(byte); + if (byte === 0x2a) state = "block_comment_star"; + break; + case "block_comment_star": + emit(byte); + if (byte === 0x2f) state = "code"; + else if (byte !== 0x2a) state = "block_comment"; + break; + case "string": + emit(byte); + if (byte === 0x5c) state = "string_escape"; + else if (byte === 0x22) state = "code"; + break; + case "string_escape": + emit(byte); + state = "string"; + break; + case "regex": + emit(byte); + if (byte === 0x5c) state = "regex_escape"; + else if (byte === 0x2f || byte === 0x0a) state = "code"; + break; + case "regex_escape": + emit(byte); + state = byte === 0x0a ? "code" : "regex"; + break; + case "include_ws": + if (isHorizSpace(byte)) { + emit(byte); + } else if (byte === 0x22) { + emit(byte); + includePathBytes = []; + state = "include_path"; + } else { + state = "code"; + processCodeByte(byte); + } + break; + case "include_path": + if (byte === 0x22) { + emitRewrittenPath(includePathBytes); + emit(byte); + includePathBytes = []; + state = "code"; + } else if ( + byte === 0x0a || + byte === 0x0d || + includePathBytes.length >= MAX_INCLUDE_PATH_BYTES + ) { + emitBuffer(includePathBytes); + includePathBytes = []; + emit(byte); + state = "code"; + } else { + includePathBytes.push(byte); + } + break; + } + } + return Buffer.from(out); + }, + + finish(): Buffer { + if (state === "include_path" && includePathBytes.length > 0) { + reserveBytes(includePathBytes.length); + const tail = Buffer.from(includePathBytes); + includePathBytes = []; + state = "code"; + return tail; + } + return Buffer.alloc(0); + }, + }; +}; diff --git a/tests/acceptance/tools/localToolContracts.test.ts b/tests/acceptance/tools/localToolContracts.test.ts index 986c4336ea7..d9463975bb2 100644 --- a/tests/acceptance/tools/localToolContracts.test.ts +++ b/tests/acceptance/tools/localToolContracts.test.ts @@ -278,6 +278,8 @@ const pathRequests: readonly [string, Record][] = [ ["inspect_nuget_nupkg", { path: nul }], ["inspect_vsix_package", { path: nul }], ["inspect_oci_image_layout", { path: nul }], + ["inspect_yara_matches", { path: nul, rule_paths: ["/tmp/rules.yar"] }], + ["inspect_yara_matches", { path: "/tmp/sample.bin", rule_paths: [nul] }], ["inspect_erlang_beam", { path: nul }], ["inspect_binary_layout", { path: nul }], ["inspect_recorded_crash", { path: nul }], diff --git a/tests/acceptance/yaraMatchesCli.test.ts b/tests/acceptance/yaraMatchesCli.test.ts new file mode 100644 index 00000000000..b5202d3e7f4 --- /dev/null +++ b/tests/acceptance/yaraMatchesCli.test.ts @@ -0,0 +1,168 @@ +import { createHash } from "node:crypto"; +import { writeFile } from "node:fs/promises"; +import { isAbsolute, join } from "node:path"; +import { expect } from "vitest"; + +import { contractNamed } from "../../src/cli/contractCliDescription.js"; +import { YARA_TOOL_CONTRACTS } from "../../src/contracts/yara/yaraToolContracts.js"; +import { analysisErrorProjectionSchema } from "../../src/domain/analysisErrorProjectionSchema.js"; +import { yaraMatchesSchema } from "../../src/domain/yara/yaraMatches.js"; +import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js"; +import { + writeYaraStub, + YARA_STUB_RULE, + YARA_STUB_SAMPLE, +} from "../fixtures/yara/yaraStub.js"; +import { cliTest } from "../support/cli/cliFixture.js"; + +const completeYaraEvidenceSchema = contractNamed( + YARA_TOOL_CONTRACTS, + "inspect_yara_matches", +).outputSchema.safeExtend({ normalized_result: yaraMatchesSchema }); +const posixCliTest = cliTest.skipIf(process.platform === "win32"); + +const workspace = async () => { + const root = await createTestTempDirectory("rea-yara-cli-"); + const command = await writeYaraStub(root); + await writeFile(join(root, "sample.bin"), YARA_STUB_SAMPLE); + await writeFile(join(root, "packers.yar"), YARA_STUB_RULE); + return { root, command }; +}; + +posixCliTest( + "scans a relative file with relative rule paths through inspect-yara-matches", + async ({ cli }) => { + const { root, command } = await workspace(); + const output = await cli.run({ + arguments: [ + "inspect-yara-matches", + "./sample.bin", + "--rule_paths", + "./packers.yar", + "--format", + "json", + ], + cwd: root, + environment: { REA_YARA_COMMAND: command, YARA_STUB_MODE: "match" }, + }); + expect(output.exitCode, output.stderr).toBe(0); + const evidence = completeYaraEvidenceSchema.parse(output.json); + // Relative caller paths reach yara as absolute paths. + expect(isAbsolute(evidence.normalized_result.artifact.path)).toBe(true); + expect(evidence.normalized_result.artifact.path).toMatch(/sample\.bin$/u); + expect(evidence.normalized_result.rule_files).toEqual([ + expect.objectContaining({ + path: expect.stringMatching(/packers\.yar$/u), + }), + ]); + expect(evidence.normalized_result.matches.map(({ rule }) => rule)).toEqual([ + "Packed", + "Plain", + ]); + }, +); + +posixCliTest( + "exits with a rule compile error naming the rule file", + async ({ cli }) => { + const { root, command } = await workspace(); + const output = await cli.run({ + arguments: [ + "inspect-yara-matches", + "./sample.bin", + "--rule_paths", + "./packers.yar", + "--format", + "json", + ], + cwd: root, + environment: { REA_YARA_COMMAND: command, YARA_STUB_MODE: "compile" }, + }); + expect(output.exitCode).toBe(1); + const error = analysisErrorProjectionSchema.parse(output.json); + expect(error.code).toBe("invalid_request"); + expect(JSON.stringify(error)).toContain("packers.yar(3)"); + }, +); + +posixCliTest( + "reports the scanned snapshot when a rule fails its final identity check", + async ({ cli }) => { + const { root, command } = await workspace(); + const sample = join(root, "sample.bin"); + const rule = join(root, "packers.yar"); + const output = await cli.run({ + arguments: [ + "inspect-yara-matches", + sample, + "--rule_paths", + rule, + "--format", + "json", + ], + cwd: root, + environment: { REA_YARA_COMMAND: command, YARA_STUB_MODE: "mutate-rule" }, + }); + expect(output.exitCode, output.stderr).toBe(1); + expect(analysisErrorProjectionSchema.parse(output.json)).toMatchObject({ + code: "artifact_changed", + details: { + path: rule, + partial_observation: { + kind: "file-snapshot-hash", + path: sample, + sha256: createHash("sha256").update(YARA_STUB_SAMPLE).digest("hex"), + bytes: YARA_STUB_SAMPLE.length, + }, + }, + }); + }, +); + +posixCliTest( + "resolves a relative REA_YARA_COMMAND against the caller's working directory", + async ({ cli }) => { + const { root } = await workspace(); + const output = await cli.run({ + arguments: [ + "inspect-yara-matches", + "./sample.bin", + "--rule_paths", + "./packers.yar", + "--format", + "json", + ], + cwd: root, + environment: { + REA_YARA_COMMAND: "./yara-stub.cjs", + YARA_STUB_MODE: "match", + }, + }); + expect(output.exitCode, output.stderr).toBe(0); + const evidence = completeYaraEvidenceSchema.parse(output.json); + expect(evidence.normalized_result.matches.map(({ rule }) => rule)).toEqual([ + "Packed", + "Plain", + ]); + }, +); + +cliTest("reports a missing yara command as unavailable", async ({ cli }) => { + const { root } = await workspace(); + const output = await cli.run({ + arguments: [ + "inspect-yara-matches", + "./sample.bin", + "--rule_paths", + "./packers.yar", + "--format", + "json", + ], + cwd: root, + environment: { REA_YARA_COMMAND: join(root, "missing-yara") }, + }); + expect(output.exitCode).not.toBe(0); + const error = analysisErrorProjectionSchema.parse(output.json); + expect(error.code).toBe("capability_unavailable"); + expect(error.remediation.action).toContain("REA_YARA_COMMAND"); +}); diff --git a/tests/boundary/cli/cliContractCommandParity.test.ts b/tests/boundary/cli/cliContractCommandParity.test.ts index 9d1ff6fb2f8..1a558fddb9e 100644 --- a/tests/boundary/cli/cliContractCommandParity.test.ts +++ b/tests/boundary/cli/cliContractCommandParity.test.ts @@ -274,7 +274,9 @@ const requiredValue = ( parameter: ContractCliParameter, ): unknown => parameter.callerPath - ? "rel/target" + ? parameter.repeatable + ? ["rel/target"] + : "rel/target" : probes(suppliedField(description, parameter)).find( (value) => value !== undefined && diff --git a/tests/boundary/mcp/absoluteLocalPathTools.test.ts b/tests/boundary/mcp/absoluteLocalPathTools.test.ts index fcfe5d50e0e..c1abf3cc8aa 100644 --- a/tests/boundary/mcp/absoluteLocalPathTools.test.ts +++ b/tests/boundary/mcp/absoluteLocalPathTools.test.ts @@ -15,6 +15,7 @@ import { DEB_PACKAGE_TOOL_CONTRACTS } from "../../../src/contracts/deb/debPackag import { NUGET_NUPKG_TOOL_CONTRACTS } from "../../../src/contracts/nuget/nupkgToolContracts.js"; import { VSIX_PACKAGE_TOOL_CONTRACTS } from "../../../src/contracts/vsix/vsixPackageToolContracts.js"; import { OCI_IMAGE_LAYOUT_TOOL_CONTRACTS } from "../../../src/contracts/oci/ociImageLayoutToolContracts.js"; +import { YARA_TOOL_CONTRACTS } from "../../../src/contracts/yara/yaraToolContracts.js"; import { RequestTrackingMcpServer } from "../../../src/server/RequestTrackingMcpServer.js"; import { toolRegistrationOptions } from "../../../src/server/toolRegistrationOptions.js"; import { createMcpSchemaValidation } from "../../fixtures/mcpSchemaValidation.js"; @@ -30,6 +31,7 @@ const CONTRACTS = [ ...NUGET_NUPKG_TOOL_CONTRACTS, ...VSIX_PACKAGE_TOOL_CONTRACTS, ...OCI_IMAGE_LAYOUT_TOOL_CONTRACTS, + ...YARA_TOOL_CONTRACTS, ...V8_CODE_CACHE_TOOL_CONTRACTS, ...MAVEN_GRADLE_METADATA_TOOL_CONTRACTS, ]; @@ -49,6 +51,7 @@ const PATH_FIELDS = { inspect_nuget_nupkg: ["path"], inspect_vsix_package: ["path"], inspect_oci_image_layout: ["path"], + inspect_yara_matches: ["path", "rule_paths"], inspect_v8_code_cache: ["path"], inspect_maven_gradle_metadata: ["path"], export_web_scripts: ["capture_path", "output_directory"], @@ -85,6 +88,8 @@ const validInput = ( output_directory: absoluteDirectory, additional_paths: [absoluteFile], }; + if (name === "inspect_yara_matches") + return { path: absoluteFile, rule_paths: [absoluteFile] }; return { path: absoluteFile }; }; @@ -93,7 +98,10 @@ const withRelativeField = ( field: string, ): Record => ({ ...validInput(name), - [field]: field === "additional_paths" ? ["sample.bin"] : "sample.bin", + [field]: + field === "additional_paths" || field === "rule_paths" + ? ["sample.bin"] + : "sample.bin", }); it("rejects one relative path field at a time on tools/list", async () => { @@ -160,6 +168,8 @@ it("rejects one relative path field at a time on tools/list", async () => { "inspect_nuget_nupkg.path", "inspect_vsix_package.path", "inspect_oci_image_layout.path", + "inspect_yara_matches.path", + "inspect_yara_matches.rule_paths", "inspect_v8_code_cache.path", "inspect_maven_gradle_metadata.path", "export_web_scripts.capture_path", diff --git a/tests/boundary/mcp/yaraMatchesMcp.test.ts b/tests/boundary/mcp/yaraMatchesMcp.test.ts new file mode 100644 index 00000000000..6394d06afc1 --- /dev/null +++ b/tests/boundary/mcp/yaraMatchesMcp.test.ts @@ -0,0 +1,138 @@ +import { writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { expect } from "vitest"; + +import { contractNamed } from "../../../src/cli/contractCliDescription.js"; +import { YARA_TOOL_CONTRACTS } from "../../../src/contracts/yara/yaraToolContracts.js"; +import { yaraMatchesSchema } from "../../../src/domain/yara/yaraMatches.js"; +import { createServer } from "../../../src/server/createServer.js"; +import { createTestBinarySession } from "../../fixtures/binarySession.js"; +import { parseMcpToolError } from "../../fixtures/mcpToolError.js"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; +import { + writeYaraStub, + YARA_STUB_RULE, + YARA_STUB_SAMPLE, + yaraStubService, +} from "../../fixtures/yara/yaraStub.js"; +import { mcpTest, type TestMcp } from "../../support/mcp/mcpFixture.js"; + +const yaraContract = contractNamed(YARA_TOOL_CONTRACTS, "inspect_yara_matches"); +const completeYaraEvidenceSchema = yaraContract.outputSchema.safeExtend({ + normalized_result: yaraMatchesSchema, +}); +const posixTest = mcpTest.skipIf(process.platform === "win32"); + +const connect = async (mcp: TestMcp, mode: string) => { + const root = await createTestTempDirectory("rea-yara-mcp-"); + const command = await writeYaraStub(root); + const sample = join(root, "sample.bin"); + await writeFile(sample, YARA_STUB_SAMPLE); + const rule = join(root, "packers.yar"); + await writeFile(rule, YARA_STUB_RULE); + const session = createTestBinarySession(() => { + throw new Error("YARA scanning must not start a deep provider"); + }); + const client = await mcp.connect( + createServer( + { kind: "session", session }, + { + yaraMatches: yaraStubService(command, { + ...process.env, + YARA_STUB_MODE: mode, + }), + }, + ), + ); + return { client, session, sample, rule }; +}; + +posixTest( + "advertises inspect_yara_matches and returns matches as Evidence", + async ({ mcp }) => { + const { client, session, sample, rule } = await connect(mcp, "match"); + try { + const advertised = (await client.listTools()).tools.find( + (tool) => tool.name === "inspect_yara_matches", + ); + expect(yaraContract.effects.writesFilesystem).toBe(true); + expect(advertised?.annotations).toMatchObject({ readOnlyHint: false }); + const response = await client.callTool({ + name: "inspect_yara_matches", + arguments: { path: sample, rule_paths: [rule] }, + }); + expect(response.isError, JSON.stringify(response.content)).not.toBe(true); + const evidence = completeYaraEvidenceSchema.parse( + response.structuredContent, + ); + expect( + evidence.normalized_result.matches.map(({ rule }) => rule), + ).toEqual(["Packed", "Plain"]); + expect(evidence.normalized_result.rule_files[0]?.path).toBe(rule); + } finally { + await session.close(); + } + }, +); + +posixTest( + "reports a rule compile error as invalid input naming the rule file", + async ({ mcp }) => { + const { client, session, sample, rule } = await connect(mcp, "compile"); + try { + const response = await client.callTool({ + name: "inspect_yara_matches", + arguments: { path: sample, rule_paths: [rule] }, + }); + const { error } = parseMcpToolError(response); + expect(error.code).toBe("invalid_request"); + expect(JSON.stringify(error)).toContain("undefined identifier"); + expect(error.remediation.action).toContain( + "import the module that provides it", + ); + } finally { + await session.close(); + } + }, +); + +mcpTest( + "reports yara unavailable without affecting other tools", + async ({ mcp }) => { + const root = await createTestTempDirectory("rea-yara-mcp-missing-"); + const sample = join(root, "sample.bin"); + await writeFile(sample, YARA_STUB_SAMPLE); + const rule = join(root, "packers.yar"); + await writeFile(rule, YARA_STUB_RULE); + const session = createTestBinarySession(() => { + throw new Error("YARA scanning must not start a deep provider"); + }); + const client = await mcp.connect( + createServer( + { kind: "session", session }, + { + environment: { + ...process.env, + REA_YARA_COMMAND: join(root, "missing-yara"), + }, + }, + ), + ); + try { + const response = await client.callTool({ + name: "inspect_yara_matches", + arguments: { path: sample, rule_paths: [rule] }, + }); + const { error } = parseMcpToolError(response); + expect(error.code).toBe("capability_unavailable"); + expect(error.remediation.action).toContain("REA_YARA_COMMAND"); + const entropy = await client.callTool({ + name: "inspect_byte_entropy", + arguments: { path: sample }, + }); + expect(entropy.isError, JSON.stringify(entropy.content)).not.toBe(true); + } finally { + await session.close(); + } + }, +); diff --git a/tests/boundary/providers/yaraMatchesProvider.test.ts b/tests/boundary/providers/yaraMatchesProvider.test.ts new file mode 100644 index 00000000000..ea00b7afa7f --- /dev/null +++ b/tests/boundary/providers/yaraMatchesProvider.test.ts @@ -0,0 +1,1730 @@ +import { createHash, randomUUID } from "node:crypto"; +import { + mkdir, + open, + readFile, + rename, + rm, + stat, + writeFile, +} from "node:fs/promises"; +import { dirname, join, parse, relative, resolve } from "node:path"; +import { describe, expect, test, vi } from "vitest"; + +import { createYaraMatchesService } from "../../../src/composition/yara.js"; +import { YaraMatchesService } from "../../../src/application/yara/YaraMatchesService.js"; +import { + primaryAnalysisError, + resolvedAnalysisError, +} from "../../../src/domain/analysisErrorBase.js"; +import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js"; +import { ok } from "../../../src/domain/result.js"; +import { + YARA_SETTING_BOUNDS, + yaraMatchesSchema, +} from "../../../src/domain/yara/yaraMatches.js"; +import { OwnedFileHandle } from "../../../src/filesystem/OwnedFileHandle.js"; +import { PrivateRuntimeRoot } from "../../../src/process/PrivateRuntimeRoot.js"; +import { cleanupOwnedProcessGroup } from "../../../src/process/ProcessOwnership.js"; +import { + YaraMatchesProvider, + type YaraLauncher, +} from "../../../src/yara/YaraMatchesProvider.js"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; +import { + interpreterLauncher, + writeYaraStub, + YARA_STUB_RULE as RULE, + YARA_STUB_SAMPLE as SAMPLE, + yaraStubService as stubService, +} from "../../fixtures/yara/yaraStub.js"; +import { expectProviderLaunchCleanup } from "../../support/process/expectProviderLaunchCleanup.js"; + +const it = test.skipIf(process.platform === "win32"); + +const stubPid = async (args: string): Promise => { + for (;;) { + try { + return Number(await readFile(`${args}.pid`, "utf8")); + } catch { + await new Promise((resolve) => setTimeout(resolve, 20)); + } + } +}; + +/** A rule file under a directory whose name holds a colon, as `a:b`. */ +const colonRule = async (root: string, name: string): Promise => { + const directory = join(root, `rea-yara-ns:rea-yara-split-${randomUUID()}`); + await mkdir(directory); + const rule = join(directory, "rule.yar"); + await writeFile(rule, `rule ${name} { condition: true }\n`); + return rule; +}; + +const fixture = async (mode: string) => { + const root = await createTestTempDirectory("rea-yara-provider-"); + const command = await writeYaraStub(root); + const sample = join(root, "sample.bin"); + await writeFile(sample, SAMPLE); + const rule = join(root, "packers.yar"); + await writeFile(rule, RULE); + const args = join(root, "args.json"); + const service = stubService(command, { + ...process.env, + YARA_STUB_MODE: mode, + YARA_STUB_ARGS: args, + }); + return { root, command, sample, rule, args, service }; +}; + +describe("inspect_yara_matches with a yara stand-in", () => { + it("binds matches to the file and rule digests and passes argv without a shell", async () => { + const { sample, rule, args, service } = await fixture("match"); + const result = await service.inspect({ path: sample, rule_paths: [rule] }); + expect(result.ok, JSON.stringify(result)).toBe(true); + if (!result.ok) return; + const report = yaraMatchesSchema.parse(result.value.normalized_result); + const recorded = JSON.parse(await readFile(args, "utf8")) as { + args: string[]; + cwd: string; + }; + expect(recorded.args.slice(0, 5)).toEqual(["-s", "-L", "-m", "-g", "-q"]); + const snapshotRuleArg = recorded.args[5]!; + const snapshotTarget = recorded.args[6]!; + expect(snapshotRuleArg).toMatch(/^rea:.+rule-0\.yar$/u); + expect(snapshotRuleArg).not.toBe(`rea:${rule}`); + expect(snapshotTarget).not.toBe(sample); + expect(recorded.cwd).toBe(parse(snapshotTarget).root); + // The owned snapshot directory is removed before inspect returns. + await expect(stat(dirname(snapshotTarget))).rejects.toMatchObject({ + code: "ENOENT", + }); + expect(report.artifact).toEqual({ + path: sample, + sha256: expect.stringMatching(/^[0-9a-f]{64}$/u), + bytes: SAMPLE.length, + }); + expect(report.rule_files).toEqual([ + { + path: rule, + sha256: expect.stringMatching(/^[0-9a-f]{64}$/u), + bytes: Buffer.byteLength(RULE), + }, + ]); + expect(report.matches).toEqual([ + { + rule: "Packed", + tags: ["packer", "upx"], + meta: [ + { identifier: "author", type: "string", value: "Analyst" }, + { identifier: "score", type: "integer", value: 7 }, + ], + string_match_count: 2, + strings: [ + { + identifier: "$mz", + file_offset: 0, + length: 4, + data: "MZ\\x90\\x00", + }, + { identifier: "$upx", file_offset: 16, length: 3, data: "UPX" }, + ], + }, + { rule: "Plain", tags: [], meta: [], string_match_count: 0, strings: [] }, + ]); + expect(report.coverage).toEqual({ + status: "complete", + matched_rules: 2, + string_matches: 2, + listed_string_matches: 2, + }); + expect(report.warnings).toEqual([ + expect.stringContaining('string "$a" may slow down scanning'), + ]); + expect(report.limits).toEqual({ + max_matches: { value: 256, source: "default" }, + max_output_bytes: { value: 64 * 1024 * 1024, source: "default" }, + command_timeout_ms: { value: 60_000, source: "default" }, + max_file_bytes: 2 * 1024 * 1024 * 1024, + }); + expect(result.value.subject).toMatchObject({ + local_path: sample, + identity: { sha256: report.artifact.sha256 }, + }); + expect(result.value.locations).toEqual([ + { kind: "artifact-path", path: sample }, + { kind: "artifact-path", path: rule }, + ]); + expect(result.value.provider.id).toBe("yara.command"); + }); + + it("passes fast_scan as -f", async () => { + const { sample, rule, args, service } = await fixture("match"); + const result = await service.inspect({ + path: sample, + rule_paths: [rule], + fast_scan: true, + }); + expect(result.ok).toBe(true); + expect(JSON.parse(await readFile(args, "utf8")).args).toContain("-f"); + if (result.ok) + expect(result.value.limitations).toContainEqual( + expect.stringContaining("lower bounds"), + ); + }); + + it("lists up to max_matches and keeps the counts", async () => { + const { sample, rule, service } = await fixture("many"); + const result = await service.inspect({ + path: sample, + rule_paths: [rule], + max_matches: 10, + }); + expect(result.ok).toBe(true); + if (!result.ok) return; + const report = yaraMatchesSchema.parse(result.value.normalized_result); + expect(report.coverage).toEqual({ + status: "partial", + matched_rules: 1, + string_matches: 50, + listed_string_matches: 10, + }); + expect(report.matches[0]?.string_match_count).toBe(50); + expect(report.matches[0]?.strings).toHaveLength(10); + expect(report.limits.max_matches).toEqual({ value: 10, source: "request" }); + expect(report.limitations).toContainEqual( + expect.stringContaining("40 of 50 string matches"), + ); + }); + + it("uses the launch seed when the call omits a control", async () => { + const root = await fixture("many"); + const service = stubService(root.command, { + ...process.env, + YARA_STUB_MODE: "many", + REA_YARA_MAX_MATCHES: "5", + }); + const result = await service.inspect({ + path: root.sample, + rule_paths: [root.rule], + }); + expect(result.ok).toBe(true); + if (result.ok) + expect( + yaraMatchesSchema.parse(result.value.normalized_result).limits + .max_matches, + ).toEqual({ value: 5, source: "setting" }); + }); + + it("refuses an invalid launch seed instead of using the default", async () => { + const root = await fixture("many"); + const service = stubService(root.command, { + ...process.env, + REA_YARA_MAX_MATCHES: "0", + }); + const result = await service.inspect({ + path: root.sample, + rule_paths: [root.rule], + }); + expect(!result.ok && result.error._tag).toBe("ConfigurationError"); + }); + + it("returns a rule compile error as an input error naming the rule file", async () => { + const { sample, rule, service } = await fixture("compile"); + const result = await service.inspect({ path: sample, rule_paths: [rule] }); + expect(result.ok).toBe(false); + if (result.ok) return; + expect(result.error).toMatchObject({ + _tag: "AnalysisInputError", + conformsToInputContract: true, + issues: [ + { + path: ["rule_paths", 0], + reason: "invalid_value", + message: `${rule}(3): rule "Bad": undefined identifier "nope"`, + }, + ], + remediationAction: expect.stringContaining( + "import the module that provides it", + ), + }); + }); + + it("does not report a scan error as a rule error", async () => { + const { sample, rule, service } = await fixture("scan-error"); + const result = await service.inspect({ path: sample, rule_paths: [rule] }); + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error._tag).not.toBe("AnalysisInputError"); + }); + + it("refuses stdout that is not yara match output", async () => { + const { sample, rule, service } = await fixture("garbage"); + const result = await service.inspect({ path: sample, rule_paths: [rule] }); + expect(!result.ok && result.error._tag).toBe("AnalysisOutputError"); + }); + + it("preserves malformed yara output as primary error when process cleanup fails", async () => { + const { command, sample, rule } = await fixture("garbage"); + let cleanupAttempts = 0; + const launcher: YaraLauncher = async (spawn) => { + const launched = await interpreterLauncher(spawn); + return { + ...launched, + cleanup: async () => { + cleanupAttempts += 1; + if (cleanupAttempts === 1) { + return { + cleaned: false, + reason: "injected yara process cleanup failure", + }; + } + return cleanupOwnedProcessGroup(launched.ownership); + }, + }; + }; + const service = stubService( + command, + { ...process.env, YARA_STUB_MODE: "garbage" }, + launcher, + ); + const result = await service.inspect({ path: sample, rule_paths: [rule] }); + expect(result.ok).toBe(false); + if (result.ok) return; + expect(result.error.cleanupIncomplete).toBe(true); + const primary = primaryAnalysisError(result.error); + expect(primary._tag).toBe("AnalysisOutputError"); + expect(primary.message).toContain("not a documented match line"); + expect(projectAnalysisError(result.error)).toMatchObject({ + code: "cleanup_incomplete", + details: { + cleanup: "incomplete", + }, + }); + await expect(service.close()).resolves.toBeUndefined(); + expect(cleanupAttempts).toBe(2); + expect(result.error.cleanupIncomplete).toBe(false); + expect(resolvedAnalysisError(result.error)).toBe(primary); + }); + + it("preserves malformed yara output as primary error when cancelled during process cleanup", async () => { + const { command, sample, rule } = await fixture("garbage"); + const controller = new AbortController(); + const launcher: YaraLauncher = async (spawn) => { + const launched = await interpreterLauncher(spawn); + return { + ...launched, + cleanup: async () => { + controller.abort("cancelled during process cleanup"); + return cleanupOwnedProcessGroup(launched.ownership); + }, + }; + }; + const service = stubService( + command, + { ...process.env, YARA_STUB_MODE: "garbage" }, + launcher, + ); + const result = await service.inspect( + { path: sample, rule_paths: [rule] }, + { signal: controller.signal }, + ); + expect(result.ok).toBe(false); + if (result.ok) return; + expect(result.error._tag).toBe("AnalysisOutputError"); + expect(result.error.message).toContain("not a documented match line"); + expect(result.error.cleanupIncomplete).toBe(false); + expect(result.error.secondaryFailures).toEqual([ + expect.objectContaining({ _tag: "AnalysisCancelledError" }), + ]); + expect(projectAnalysisError(result.error)).toMatchObject({ + details: { + secondary_failures: [expect.objectContaining({ code: "cancelled" })], + }, + }); + }); + + it("stops output beyond max_output_bytes with the setting as its limit", async () => { + const { sample, rule, service } = await fixture("flood"); + const result = await service.inspect({ + path: sample, + rule_paths: [rule], + max_output_bytes: 4096, + }); + expect(result.ok).toBe(false); + if (result.ok) return; + expect(result.error).toMatchObject({ + _tag: "AnalysisResourceConstraintError", + limit: expect.objectContaining({ + setting: "yara.max_output_bytes", + effective_value: 4096, + }), + }); + }); + + it("stops a scan at command_timeout_ms", async () => { + const { sample, rule, args, service } = await fixture("hang"); + const result = await service.inspect({ + path: sample, + rule_paths: [rule], + command_timeout_ms: 300, + }); + expect(result.ok).toBe(false); + if (result.ok) return; + expect(result.error).toMatchObject({ + _tag: "AnalysisTimeoutError", + limit: expect.objectContaining({ + setting: "yara.command_timeout_ms", + effective_value: 300, + }), + }); + expect(result.error.cleanupIncomplete).toBe(false); + await expectProviderLaunchCleanup([ + { pid: await stubPid(args), cwd: undefined }, + ]); + await expect(service.close()).resolves.toBeUndefined(); + }); + + it("cancels a running scan and leaves nothing to clean up", async () => { + const { sample, rule, args, service } = await fixture("hang"); + const controller = new AbortController(); + const pending = service.inspect( + { path: sample, rule_paths: [rule] }, + { signal: controller.signal }, + ); + const pid = await stubPid(args); + controller.abort(); + const result = await pending; + expect(result.ok).toBe(false); + if (result.ok) return; + expect(result.error._tag).toBe("AnalysisCancelledError"); + expect(result.error.cleanupIncomplete).toBe(false); + await expectProviderLaunchCleanup([{ pid, cwd: undefined }]); + await expect(service.close()).resolves.toBeUndefined(); + }); + + it("retains a failed process cleanup and retries it before the next scan", async () => { + const { command, sample, rule, args } = await fixture("hang"); + let attempts = 0; + const launcher: YaraLauncher = async (spawn) => { + const launched = await interpreterLauncher(spawn); + const cleanup = + launched.cleanup ?? + (() => cleanupOwnedProcessGroup(launched.ownership)); + return { + ...launched, + cleanup: async () => { + attempts += 1; + if (attempts === 1) throw new Error("injected cleanup failure"); + return cleanup(); + }, + }; + }; + const service = stubService( + command, + { ...process.env, YARA_STUB_MODE: "hang", YARA_STUB_ARGS: args }, + launcher, + ); + const first = await service.inspect({ + path: sample, + rule_paths: [rule], + command_timeout_ms: 300, + }); + expect(first.ok).toBe(false); + if (first.ok) return; + expect(first.error.cleanupIncomplete).toBe(true); + const pid = await stubPid(args); + const second = await service.inspect({ + path: sample, + rule_paths: [rule], + command_timeout_ms: 300, + }); + expect(second.ok).toBe(false); + if (second.ok) return; + expect(second.error._tag).toBe("AnalysisTimeoutError"); + expect(second.error.cleanupIncomplete).toBe(false); + await expectProviderLaunchCleanup([{ pid, cwd: undefined }]); + await expect(service.close()).resolves.toBeUndefined(); + }); + + it("compiles the hashed rule path even when it contains a colon", async () => { + const { root, command, sample, args } = await fixture("resolve"); + const rule = await colonRule(root, "ColonRule"); + const service = stubService(command, { + ...process.env, + YARA_STUB_MODE: "resolve", + YARA_STUB_ARGS: args, + }); + const result = await service.inspect({ path: sample, rule_paths: [rule] }); + expect(result.ok, JSON.stringify(result)).toBe(true); + if (!result.ok) return; + const report = yaraMatchesSchema.parse(result.value.normalized_result); + expect(report.matches.map((match) => match.rule)).toEqual(["ColonRule"]); + expect(report.rule_files.map((file) => file.path)).toEqual([rule]); + }); + + it("never compiles another file when a colon rule path is replaced after hashing", async () => { + const { root, command, sample, args } = await fixture("resolve"); + const rule = await colonRule(root, "HashedRule"); + const planted: string[] = []; + // Between hashing and launch the selected file disappears and a file + // appears where yara's NAMESPACE:FILE split of a bare path would point. + const launcher: YaraLauncher = async (spawn) => { + await rm(rule); + const split = rule.slice(rule.indexOf(":") + 1); + const decoy = resolve(spawn.cwd ?? process.cwd(), split); + try { + await mkdir(dirname(decoy)); + planted.push(dirname(decoy)); + await writeFile(decoy, "rule DecoyRule { condition: true }\n"); + } catch { + // A working directory REA chose may not be writable; nothing to plant. + } + return interpreterLauncher(spawn); + }; + const service = stubService( + command, + { ...process.env, YARA_STUB_MODE: "resolve", YARA_STUB_ARGS: args }, + launcher, + ); + try { + const result = await service.inspect({ + path: sample, + rule_paths: [rule], + }); + // Because yara compiles the owned snapshot bound to the hashed digest, + // deleting the original rule path and planting a decoy after hashing + // still compiles HashedRule and never DecoyRule. + expect(result.ok, JSON.stringify(result)).toBe(true); + if (!result.ok) return; + const report = yaraMatchesSchema.parse(result.value.normalized_result); + expect(report.matches.map((match) => match.rule)).toEqual(["HashedRule"]); + expect(report.rule_files.map((file) => file.path)).toEqual([rule]); + } finally { + await Promise.all( + planted.map((path) => rm(path, { recursive: true, force: true })), + ); + } + }); + + it("scans the owned snapshot even when a parent directory is swapped before yara opens the file", async () => { + const { root, command, args } = await fixture("resolve"); + const liveDir = join(root, "live"); + const decoyDir = join(root, "decoy"); + const backupDir = join(root, "backup"); + await mkdir(liveDir); + await mkdir(decoyDir); + const liveSample = join(liveDir, "sample.bin"); + const liveRule = join(liveDir, "rules.yar"); + await writeFile(liveSample, SAMPLE); + await writeFile(liveRule, "rule HashedRule { condition: true }\n"); + await writeFile(join(decoyDir, "sample.bin"), "DECOY BYTES"); + await writeFile( + join(decoyDir, "rules.yar"), + "rule SwappedRule { condition: true }\n", + ); + let swapped = false; + const launcher: YaraLauncher = async (spawn) => { + // Simulate a POSIX parent-directory rename TOCTOU between hashing and + // yara opening the paths; restore the directory in finally below. + await rename(liveDir, backupDir); + await rename(decoyDir, liveDir); + swapped = true; + return interpreterLauncher(spawn); + }; + const service = stubService( + command, + { ...process.env, YARA_STUB_MODE: "resolve", YARA_STUB_ARGS: args }, + launcher, + ); + try { + const result = await service.inspect({ + path: liveSample, + rule_paths: [liveRule], + }); + expect(result.ok, JSON.stringify(result)).toBe(true); + if (!result.ok) return; + const report = yaraMatchesSchema.parse(result.value.normalized_result); + expect(report.matches.map((match) => match.rule)).toEqual(["HashedRule"]); + expect(report.artifact).toEqual({ + path: liveSample, + sha256: createHash("sha256").update(SAMPLE).digest("hex"), + bytes: SAMPLE.length, + }); + expect(report.rule_files).toEqual([ + { + path: liveRule, + sha256: createHash("sha256") + .update("rule HashedRule { condition: true }\n") + .digest("hex"), + bytes: Buffer.byteLength("rule HashedRule { condition: true }\n"), + }, + ]); + } finally { + if (swapped) { + await rename(liveDir, decoyDir); + await rename(backupDir, liveDir); + } + } + }); + + it("preserves relative include lookup when staging rule files", async () => { + const { root, command, sample, args } = await fixture("resolve"); + const rulesDir = join(root, "rules"); + await mkdir(rulesDir); + const common = join(rulesDir, "common.yar"); + await writeFile(common, "rule CommonRule { condition: true }\n"); + const mainRuleText = + 'include "common.yar"\nrule MainRule { condition: true }\n'; + const mainRule = join(rulesDir, "main.yar"); + await writeFile(mainRule, mainRuleText); + const service = stubService(command, { + ...process.env, + YARA_STUB_MODE: "resolve", + YARA_STUB_ARGS: args, + }); + const result = await service.inspect({ + path: sample, + rule_paths: [mainRule], + }); + expect(result.ok, JSON.stringify(result)).toBe(true); + if (!result.ok) return; + const report = yaraMatchesSchema.parse(result.value.normalized_result); + expect(report.matches.map((match) => match.rule)).toEqual([ + "CommonRule", + "MainRule", + ]); + // The reported rule digest and byte length remain bound to the original rule file. + expect(report.rule_files).toEqual([ + { + path: mainRule, + sha256: createHash("sha256").update(mainRuleText).digest("hex"), + bytes: Buffer.byteLength(mainRuleText), + }, + ]); + }); + + it("reports a missing include as an input error with include repair advice", async () => { + const { root, command, sample, args } = await fixture("resolve"); + const rulesDir = join(root, "rules"); + await mkdir(rulesDir); + const mainRule = join(rulesDir, "main.yar"); + await writeFile( + mainRule, + 'include "common.yar"\nrule MainRule { condition: true }\n', + ); + const service = stubService(command, { + ...process.env, + YARA_STUB_MODE: "resolve", + YARA_STUB_ARGS: args, + }); + const result = await service.inspect({ + path: sample, + rule_paths: [mainRule], + }); + expect(result.ok).toBe(false); + if (result.ok) return; + expect(result.error).toMatchObject({ + _tag: "AnalysisInputError", + conformsToInputContract: true, + issues: [ + { + path: ["rule_paths", 0], + reason: "invalid_value", + message: `${mainRule}(1): can't open include file: ${join(rulesDir, "common.yar")}`, + }, + ], + remediationAction: expect.stringContaining( + "a relative include resolves against the directory of the rule file that includes it", + ), + diagnostics: { + compile_errors: [ + { + kind: "include", + source: mainRule, + line: 1, + rule: null, + }, + ], + }, + }); + }); + + it("gives a duplicated string the scope-aware duplicate repair", async () => { + const { sample, rule, service } = await fixture("duplicate-string"); + const result = await service.inspect({ path: sample, rule_paths: [rule] }); + expect(result.ok).toBe(false); + if (result.ok) return; + expect(result.error).toMatchObject({ + _tag: "AnalysisInputError", + issues: [ + { + path: ["rule_paths", 0], + message: `${rule}(4): rule "Dup": duplicated string identifier "$a"`, + }, + ], + remediationAction: expect.stringContaining( + "string, tag and metadata identifiers within their rule", + ), + diagnostics: { compile_errors: [{ kind: "duplicate", rule: "Dup" }] }, + }); + }); + + it("retains completed Evidence and retries failed snapshot directory cleanup before the next scan", async () => { + const { command, sample, rule } = await fixture("match"); + let firstRootPath: string | undefined; + let firstCloseAttempts = 0; + const provider = new YaraMatchesProvider({ + environment: { ...process.env, YARA_STUB_MODE: "match" }, + selectCommand: () => ok(command), + launcher: interpreterLauncher, + createRuntime: async () => { + const real = await PrivateRuntimeRoot.create({ prefix: "rea-yara-" }); + if (firstRootPath !== undefined) return real; + firstRootPath = real.path; + return { + path: real.path, + close: async () => { + firstCloseAttempts += 1; + if (firstCloseAttempts === 1) + throw new Error("injected snapshot root cleanup failure"); + return real.close(); + }, + }; + }, + }); + const service = new YaraMatchesService(provider, process.env); + const first = await service.inspect({ path: sample, rule_paths: [rule] }); + expect(first.ok).toBe(false); + if (first.ok) return; + expect(first.error.cleanupIncomplete).toBe(true); + expect(firstRootPath).toBeDefined(); + // Completed matches survive failed snapshot cleanup as full Evidence. + const partialEvidence = first.error.partialObservation as { + normalized_result?: unknown; + operation?: string; + }; + expect(partialEvidence?.operation).toBe("inspect_yara_matches"); + const retainedReport = yaraMatchesSchema.parse( + partialEvidence?.normalized_result, + ); + expect(retainedReport.matches.map((match) => match.rule)).toEqual([ + "Packed", + "Plain", + ]); + // Second scan retries removing the retained snapshot root before proceeding. + const second = await service.inspect({ path: sample, rule_paths: [rule] }); + expect(second.ok, JSON.stringify(second)).toBe(true); + expect(firstCloseAttempts).toBe(2); + expect(first.error.cleanupIncomplete).toBe(false); + await expect(stat(firstRootPath!)).rejects.toMatchObject({ + code: "ENOENT", + }); + await expect(service.close()).resolves.toBeUndefined(); + }); + + it("retains completed Evidence when cancelled during snapshot directory removal", async () => { + const { command, sample, rule } = await fixture("match"); + const controller = new AbortController(); + const provider = new YaraMatchesProvider({ + environment: { ...process.env, YARA_STUB_MODE: "match" }, + selectCommand: () => ok(command), + launcher: interpreterLauncher, + createRuntime: async () => { + const real = await PrivateRuntimeRoot.create({ prefix: "rea-yara-" }); + return { + path: real.path, + close: async () => { + controller.abort("cancelled during cleanup"); + return real.close(); + }, + }; + }, + }); + const service = new YaraMatchesService(provider, process.env); + const result = await service.inspect( + { path: sample, rule_paths: [rule] }, + { signal: controller.signal }, + ); + expect(result.ok).toBe(false); + if (result.ok) return; + expect(result.error._tag).toBe("AnalysisCancelledError"); + expect(result.error.cleanupIncomplete).toBe(false); + const partialEvidence = result.error.partialObservation as { + normalized_result?: unknown; + operation?: string; + }; + expect(partialEvidence?.operation).toBe("inspect_yara_matches"); + const retainedReport = yaraMatchesSchema.parse( + partialEvidence?.normalized_result, + ); + expect(retainedReport.matches.map((match) => match.rule)).toEqual([ + "Packed", + "Plain", + ]); + }); + + it("preserves primary error and attaches caller cancellation when cancelled during snapshot directory removal", async () => { + const { command, sample, rule } = await fixture("compile"); + const controller = new AbortController(); + const provider = new YaraMatchesProvider({ + environment: { ...process.env, YARA_STUB_MODE: "compile" }, + selectCommand: () => ok(command), + launcher: interpreterLauncher, + createRuntime: async () => { + const real = await PrivateRuntimeRoot.create({ prefix: "rea-yara-" }); + return { + path: real.path, + close: async () => { + controller.abort("cancelled during snapshot removal"); + return real.close(); + }, + }; + }, + }); + const service = new YaraMatchesService(provider, process.env); + const result = await service.inspect( + { path: sample, rule_paths: [rule] }, + { signal: controller.signal }, + ); + expect(result.ok).toBe(false); + if (result.ok) return; + expect(result.error._tag).toBe("AnalysisInputError"); + expect(result.error.cleanupIncomplete).toBe(false); + expect(result.error.secondaryFailures).toEqual([ + expect.objectContaining({ _tag: "AnalysisCancelledError" }), + ]); + expect(projectAnalysisError(result.error)).toMatchObject({ + details: { + secondary_failures: [expect.objectContaining({ code: "cancelled" })], + }, + }); + }); + + it("preserves primary error, cleanup failure, and caller cancellation when snapshot removal fails while cancelled", async () => { + const { command, sample, rule } = await fixture("compile"); + const controller = new AbortController(); + let closeAttempts = 0; + const provider = new YaraMatchesProvider({ + environment: { ...process.env, YARA_STUB_MODE: "compile" }, + selectCommand: () => ok(command), + launcher: interpreterLauncher, + createRuntime: async () => { + const real = await PrivateRuntimeRoot.create({ prefix: "rea-yara-" }); + return { + path: real.path, + close: async () => { + closeAttempts += 1; + if (closeAttempts === 1) { + controller.abort("cancelled during failing snapshot removal"); + throw new Error("injected snapshot removal failure"); + } + return real.close(); + }, + }; + }, + }); + const service = new YaraMatchesService(provider, process.env); + const result = await service.inspect( + { path: sample, rule_paths: [rule] }, + { signal: controller.signal }, + ); + expect(result.ok).toBe(false); + if (result.ok) return; + expect(result.error.cleanupIncomplete).toBe(true); + const primary = primaryAnalysisError(result.error); + expect(primary._tag).toBe("AnalysisInputError"); + expect(primary.secondaryFailures).toEqual([ + expect.objectContaining({ _tag: "AnalysisCancelledError" }), + ]); + await expect(service.close()).resolves.toBeUndefined(); + expect(closeAttempts).toBe(2); + expect(result.error.cleanupIncomplete).toBe(false); + }); + + it("retains completed Evidence when yara process cleanup fails and retries cleanup on close", async () => { + const { command, sample, rule } = await fixture("match"); + let cleanupAttempts = 0; + const launcher: YaraLauncher = async (spawn) => { + const launched = await interpreterLauncher(spawn); + return { + ...launched, + cleanup: async () => { + cleanupAttempts += 1; + if (cleanupAttempts === 1) { + return { + cleaned: false, + reason: "injected yara process cleanup failure", + }; + } + return cleanupOwnedProcessGroup(launched.ownership); + }, + }; + }; + const service = stubService( + command, + { ...process.env, YARA_STUB_MODE: "match" }, + launcher, + ); + const first = await service.inspect({ path: sample, rule_paths: [rule] }); + expect(first.ok).toBe(false); + if (first.ok) return; + expect(first.error.cleanupIncomplete).toBe(true); + const partialEvidence = first.error.partialObservation as { + normalized_result?: unknown; + operation?: string; + }; + expect(partialEvidence?.operation).toBe("inspect_yara_matches"); + const retainedReport = yaraMatchesSchema.parse( + partialEvidence?.normalized_result, + ); + expect(retainedReport.matches.map((match) => match.rule)).toEqual([ + "Packed", + "Plain", + ]); + await expect(service.close()).resolves.toBeUndefined(); + expect(cleanupAttempts).toBe(2); + expect(first.error.cleanupIncomplete).toBe(false); + }); + + it("retains completed Evidence when cancelled during yara process cleanup", async () => { + const { command, sample, rule } = await fixture("match"); + const controller = new AbortController(); + const launcher: YaraLauncher = async (spawn) => { + const launched = await interpreterLauncher(spawn); + return { + ...launched, + cleanup: async () => { + controller.abort("cancelled during process cleanup"); + return cleanupOwnedProcessGroup(launched.ownership); + }, + }; + }; + const service = stubService( + command, + { ...process.env, YARA_STUB_MODE: "match" }, + launcher, + ); + const result = await service.inspect( + { path: sample, rule_paths: [rule] }, + { signal: controller.signal }, + ); + expect(result.ok).toBe(false); + if (result.ok) return; + expect(result.error._tag).toBe("AnalysisCancelledError"); + expect(result.error.cleanupIncomplete).toBe(false); + const partialEvidence = result.error.partialObservation as { + normalized_result?: unknown; + operation?: string; + }; + expect(partialEvidence?.operation).toBe("inspect_yara_matches"); + const retainedReport = yaraMatchesSchema.parse( + partialEvidence?.normalized_result, + ); + expect(retainedReport.matches.map((match) => match.rule)).toEqual([ + "Packed", + "Plain", + ]); + }); + + it("does not retain unverified matches on process cleanup cancellation when a rule snapshot changed", async () => { + const { command, sample, rule } = await fixture("mutate-rule"); + const controller = new AbortController(); + const launcher: YaraLauncher = async (spawn) => { + const launched = await interpreterLauncher(spawn); + return { + ...launched, + cleanup: async () => { + controller.abort("cancelled during process cleanup"); + return cleanupOwnedProcessGroup(launched.ownership); + }, + }; + }; + const service = stubService( + command, + { ...process.env, YARA_STUB_MODE: "mutate-rule" }, + launcher, + ); + const result = await service.inspect( + { path: sample, rule_paths: [rule] }, + { signal: controller.signal }, + ); + expect(result.ok).toBe(false); + if (result.ok) return; + expect(result.error._tag).toBe("AnalysisCancelledError"); + expect(result.error.partialObservation).toEqual({ + kind: "file-snapshot-hash", + path: sample, + sha256: createHash("sha256").update(SAMPLE).digest("hex"), + bytes: SAMPLE.length, + }); + }); + + const abortDuringFinalSnapshotVerification = ( + controller: AbortController, + onAbort: () => void, + ) => { + return async (path: string) => { + const handle = await open(path, "wx", 0o600); + if (!path.endsWith("target.bin")) return handle; + return new Proxy(handle, { + get(target, property, receiver) { + if (property === "stat") { + return async (options?: Parameters[0]) => { + const stats = await target.stat(options); + return new Proxy(stats, { + get(statsTarget, statsProperty, statsReceiver) { + if (statsProperty === "dev" && !controller.signal.aborted) { + onAbort(); + controller.abort( + "cancelled during final snapshot verification", + ); + } + const value = Reflect.get( + statsTarget, + statsProperty, + statsReceiver, + ); + return typeof value === "function" + ? value.bind(statsTarget) + : value; + }, + }); + }; + } + const value = Reflect.get(target, property, receiver); + return typeof value === "function" ? value.bind(target) : value; + }, + }); + }; + }; + + it("retains completed Evidence when cancelled during final snapshot verification", async () => { + const { command, sample, rule } = await fixture("match"); + const controller = new AbortController(); + let abortedDuringVerification = false; + const provider = new YaraMatchesProvider({ + environment: { ...process.env, YARA_STUB_MODE: "match" }, + selectCommand: () => ok(command), + launcher: interpreterLauncher, + openSnapshotFile: abortDuringFinalSnapshotVerification(controller, () => { + abortedDuringVerification = true; + }), + }); + const service = new YaraMatchesService(provider, process.env); + const result = await service.inspect( + { path: sample, rule_paths: [rule] }, + { signal: controller.signal }, + ); + expect(abortedDuringVerification).toBe(true); + expect(result.ok).toBe(false); + if (result.ok) return; + expect(result.error._tag).toBe("AnalysisCancelledError"); + expect(result.error.cleanupIncomplete).toBe(false); + const partialEvidence = result.error.partialObservation as { + normalized_result?: unknown; + operation?: string; + }; + expect(partialEvidence?.operation).toBe("inspect_yara_matches"); + const retainedReport = yaraMatchesSchema.parse( + partialEvidence?.normalized_result, + ); + expect(retainedReport.matches.map((match) => match.rule)).toEqual([ + "Packed", + "Plain", + ]); + }); + + it("does not retain unverified matches when cancelled during final snapshot verification after a rule snapshot changed", async () => { + const { command, sample, rule } = await fixture("mutate-rule"); + const controller = new AbortController(); + let abortedDuringVerification = false; + const provider = new YaraMatchesProvider({ + environment: { ...process.env, YARA_STUB_MODE: "mutate-rule" }, + selectCommand: () => ok(command), + launcher: interpreterLauncher, + openSnapshotFile: abortDuringFinalSnapshotVerification(controller, () => { + abortedDuringVerification = true; + }), + }); + const service = new YaraMatchesService(provider, process.env); + const result = await service.inspect( + { path: sample, rule_paths: [rule] }, + { signal: controller.signal }, + ); + expect(abortedDuringVerification).toBe(true); + expect(result.ok).toBe(false); + if (result.ok) return; + expect(result.error._tag).toBe("AnalysisCancelledError"); + expect(result.error.cleanupIncomplete).toBe(false); + expect(result.error.partialObservation).toEqual({ + kind: "file-snapshot-hash", + path: sample, + sha256: createHash("sha256").update(SAMPLE).digest("hex"), + bytes: SAMPLE.length, + }); + }); + + it("closes staged file handles before removing the snapshot root and retries in order", async () => { + const { command, sample, rule } = await fixture("match"); + const events: string[] = []; + let firstRootPath: string | undefined; + let failedHandleOnce = false; + let handleCloseAttempts = 0; + const provider = new YaraMatchesProvider({ + environment: { ...process.env, YARA_STUB_MODE: "match" }, + selectCommand: () => ok(command), + launcher: interpreterLauncher, + createRuntime: async () => { + const real = await PrivateRuntimeRoot.create({ prefix: "rea-yara-" }); + if (firstRootPath !== undefined) return real; + firstRootPath = real.path; + return { + path: real.path, + close: async () => { + events.push("root-close"); + return real.close(); + }, + }; + }, + openSnapshotFile: async (path) => { + const handle = await open(path, "wx", 0o600); + if (failedHandleOnce || !path.endsWith("rule-0.yar")) return handle; + failedHandleOnce = true; + return new Proxy(handle, { + get(target, property, receiver) { + if (property === "close") { + return async () => { + handleCloseAttempts += 1; + if (handleCloseAttempts === 1) { + events.push("handle-close-fail"); + throw new Error("injected staged handle close failure"); + } + events.push("handle-close-ok"); + return target.close(); + }; + } + const value = Reflect.get(target, property, receiver); + return typeof value === "function" ? value.bind(target) : value; + }, + }); + }, + }); + const service = new YaraMatchesService(provider, process.env); + const first = await service.inspect({ path: sample, rule_paths: [rule] }); + expect(first.ok).toBe(false); + if (first.ok) return; + expect(first.error.cleanupIncomplete).toBe(true); + // The snapshot root must NOT be removed while a child handle failed to close. + expect(events).toEqual(["handle-close-fail"]); + expect(firstRootPath).toBeDefined(); + await expect(stat(firstRootPath!)).resolves.toBeDefined(); + // Retry on close() must close the handle first, then remove the root. + await expect(service.close()).resolves.toBeUndefined(); + expect(events).toEqual([ + "handle-close-fail", + "handle-close-ok", + "root-close", + ]); + expect(first.error.cleanupIncomplete).toBe(false); + await expect(stat(firstRootPath!)).rejects.toMatchObject({ + code: "ENOENT", + }); + }); + + it("retains completed target file identity when target snapshot handle close fails", async () => { + const { command, sample, rule } = await fixture("match"); + let failedCloseOnce = false; + let closeAttempts = 0; + const provider = new YaraMatchesProvider({ + environment: { ...process.env, YARA_STUB_MODE: "match" }, + selectCommand: () => ok(command), + launcher: interpreterLauncher, + openSnapshotFile: async (path) => { + const handle = await open(path, "wx", 0o600); + if (failedCloseOnce || !path.endsWith("target.bin")) return handle; + failedCloseOnce = true; + return new Proxy(handle, { + get(target, property, receiver) { + if (property === "close") { + return async () => { + closeAttempts += 1; + if (closeAttempts === 1) + throw new Error("injected target handle close failure"); + return target.close(); + }; + } + const value = Reflect.get(target, property, receiver); + return typeof value === "function" ? value.bind(target) : value; + }, + }); + }, + }); + const service = new YaraMatchesService(provider, process.env); + const result = await service.inspect({ path: sample, rule_paths: [rule] }); + expect(result.ok).toBe(false); + if (result.ok) return; + expect(result.error.cleanupIncomplete).toBe(true); + expect(result.error.partialObservation).toEqual({ + kind: "file-snapshot-hash", + path: sample, + sha256: createHash("sha256").update(SAMPLE).digest("hex"), + bytes: SAMPLE.length, + }); + await expect(service.close()).resolves.toBeUndefined(); + expect(closeAttempts).toBe(2); + expect(result.error.cleanupIncomplete).toBe(false); + }); + + it("retains completed target file identity when cancelled during target snapshot handle close", async () => { + const { command, sample, rule } = await fixture("match"); + const controller = new AbortController(); + const provider = new YaraMatchesProvider({ + environment: { ...process.env, YARA_STUB_MODE: "match" }, + selectCommand: () => ok(command), + launcher: interpreterLauncher, + openSnapshotFile: async (path) => { + const handle = await open(path, "wx", 0o600); + if (!path.endsWith("target.bin")) return handle; + return new Proxy(handle, { + get(target, property, receiver) { + if (property === "close") { + return async () => { + controller.abort("cancelled during target handle close"); + return target.close(); + }; + } + const value = Reflect.get(target, property, receiver); + return typeof value === "function" ? value.bind(target) : value; + }, + }); + }, + }); + const service = new YaraMatchesService(provider, process.env); + const result = await service.inspect( + { path: sample, rule_paths: [rule] }, + { signal: controller.signal }, + ); + expect(result.ok).toBe(false); + if (result.ok) return; + expect(result.error._tag).toBe("AnalysisCancelledError"); + expect(result.error.cleanupIncomplete).toBe(false); + expect(result.error.partialObservation).toEqual({ + kind: "file-snapshot-hash", + path: sample, + sha256: createHash("sha256").update(SAMPLE).digest("hex"), + bytes: SAMPLE.length, + }); + }); + + it("retains completed rule identity when rule source handle close fails", async () => { + const { root, command, sample, rule } = await fixture("match"); + const secondText = "rule Second { condition: true }\n"; + const second = join(root, "second.yar"); + await writeFile(second, secondText); + const secondStat = await stat(second, { bigint: true }); + let closeAttempts = 0; + const nativeClose = OwnedFileHandle.prototype.close; + const closeSpy = vi + .spyOn(OwnedFileHandle.prototype, "close") + .mockImplementation(async function (this: OwnedFileHandle) { + if (this.handle.fd >= 0) { + const current = await this.handle.stat({ bigint: true }); + if ( + current.dev === secondStat.dev && + current.ino === secondStat.ino + ) { + closeAttempts += 1; + if (closeAttempts === 1) + throw new Error("injected rule source handle close failure"); + } + } + return nativeClose.call(this); + }); + const service = stubService(command, { + ...process.env, + YARA_STUB_MODE: "match", + }); + try { + const result = await service.inspect({ + path: sample, + rule_paths: [rule, second], + }); + expect(result.ok).toBe(false); + if (result.ok) return; + expect(result.error.cleanupIncomplete).toBe(true); + const expectedSecondObservation = { + kind: "file-snapshot-hash", + path: second, + sha256: createHash("sha256").update(secondText).digest("hex"), + bytes: Buffer.byteLength(secondText), + }; + const expectedFirstRuleObservation = { + argument: "rule_paths[0]", + observation: { + kind: "file-snapshot-hash", + path: rule, + sha256: createHash("sha256").update(RULE).digest("hex"), + bytes: Buffer.byteLength(RULE), + }, + }; + expect(result.error.partialObservation).toEqual( + expectedSecondObservation, + ); + expect(result.error.argumentObservations).toEqual([ + expectedFirstRuleObservation, + ]); + expect(projectAnalysisError(result.error)).toMatchObject({ + details: { + partial_observation: expectedSecondObservation, + argument_observations: [expectedFirstRuleObservation], + }, + }); + await expect(service.close()).resolves.toBeUndefined(); + expect(closeAttempts).toBe(2); + expect(result.error.cleanupIncomplete).toBe(false); + } finally { + closeSpy.mockRestore(); + await service.close(); + } + }); + + it("retains completed target identity when target source handle close fails", async () => { + const { command, sample, rule } = await fixture("match"); + const sampleStat = await stat(sample, { bigint: true }); + let closeAttempts = 0; + const nativeClose = OwnedFileHandle.prototype.close; + const closeSpy = vi + .spyOn(OwnedFileHandle.prototype, "close") + .mockImplementation(async function (this: OwnedFileHandle) { + if (this.handle.fd >= 0) { + const current = await this.handle.stat({ bigint: true }); + if ( + current.dev === sampleStat.dev && + current.ino === sampleStat.ino + ) { + closeAttempts += 1; + if (closeAttempts === 1) + throw new Error("injected target source handle close failure"); + } + } + return nativeClose.call(this); + }); + const service = stubService(command, { + ...process.env, + YARA_STUB_MODE: "match", + }); + try { + const result = await service.inspect({ + path: sample, + rule_paths: [rule], + }); + expect(result.ok).toBe(false); + if (result.ok) return; + expect(result.error.cleanupIncomplete).toBe(true); + const expectedTargetObservation = { + kind: "file-snapshot-hash", + path: sample, + sha256: createHash("sha256").update(SAMPLE).digest("hex"), + bytes: SAMPLE.length, + }; + const expectedRuleObservation = { + argument: "rule_paths[0]", + observation: { + kind: "file-snapshot-hash", + path: rule, + sha256: createHash("sha256").update(RULE).digest("hex"), + bytes: Buffer.byteLength(RULE), + }, + }; + expect(result.error.partialObservation).toEqual( + expectedTargetObservation, + ); + expect(result.error.argumentObservations).toEqual([ + expectedRuleObservation, + ]); + expect(projectAnalysisError(result.error)).toMatchObject({ + details: { + partial_observation: expectedTargetObservation, + argument_observations: [expectedRuleObservation], + }, + }); + await expect(service.close()).resolves.toBeUndefined(); + expect(closeAttempts).toBe(2); + expect(result.error.cleanupIncomplete).toBe(false); + } finally { + closeSpy.mockRestore(); + await service.close(); + } + }); + + it("reports a missing yara command as unavailable with remediation", async () => { + const { root, sample, rule } = await fixture("match"); + const service = createYaraMatchesService({ + ...process.env, + REA_YARA_COMMAND: join(root, "missing-yara"), + }); + const result = await service.inspect({ path: sample, rule_paths: [rule] }); + expect(result.ok).toBe(false); + if (result.ok) return; + expect(result.error._tag).toBe("AnalysisCapabilityUnavailableError"); + expect(result.error.userMessage).toContain("REA_YARA_COMMAND"); + }); + + it("reports yara missing from PATH as unavailable", async () => { + const { root, sample, rule } = await fixture("match"); + const service = createYaraMatchesService({ PATH: root }); + const result = await service.inspect({ path: sample, rule_paths: [rule] }); + expect(!result.ok && result.error._tag).toBe( + "AnalysisCapabilityUnavailableError", + ); + }); + + it("refuses a missing rule file before launching yara", async () => { + const { root, sample, args, service } = await fixture("match"); + const missing = join(root, "missing.yar"); + const result = await service.inspect({ + path: sample, + rule_paths: [missing], + }); + expect(result.ok).toBe(false); + await expect(readFile(args)).rejects.toMatchObject({ code: "ENOENT" }); + }); + + it("retains completed rule identities when a later rule file fails admission", async () => { + const { root, sample, rule, args, service } = await fixture("match"); + const missing = join(root, "missing.yar"); + const result = await service.inspect({ + path: sample, + rule_paths: [rule, missing], + }); + expect(result.ok).toBe(false); + if (result.ok) return; + await expect(readFile(args)).rejects.toMatchObject({ code: "ENOENT" }); + expect(result.error).toMatchObject({ + _tag: "AnalysisInputError", + issues: [expect.objectContaining({ path: ["rule_paths", 1] })], + }); + expect(result.error.partialObservation).toBeUndefined(); + const expectedRuleObservation = { + argument: "rule_paths[0]", + observation: { + kind: "file-snapshot-hash", + path: rule, + sha256: createHash("sha256").update(RULE).digest("hex"), + bytes: Buffer.byteLength(RULE), + }, + }; + expect(result.error.argumentObservations).toEqual([ + expectedRuleObservation, + ]); + expect(projectAnalysisError(result.error)).toMatchObject({ + details: { + argument_observations: [expectedRuleObservation], + }, + }); + }); + + it("retains completed rule identities when target admission fails", async () => { + const { root, rule, args, service } = await fixture("match"); + const secondText = "rule Second { condition: true }\n"; + const second = join(root, "second.yar"); + await writeFile(second, secondText); + const missingTarget = join(root, "missing-target.bin"); + const result = await service.inspect({ + path: missingTarget, + rule_paths: [rule, second], + }); + expect(result.ok).toBe(false); + if (result.ok) return; + await expect(readFile(args)).rejects.toMatchObject({ code: "ENOENT" }); + expect(result.error).toMatchObject({ + _tag: "AnalysisInputError", + issues: [expect.objectContaining({ path: ["path"] })], + }); + expect(result.error.partialObservation).toBeUndefined(); + const expectedRuleObservations = [ + { + argument: "rule_paths[0]", + observation: { + kind: "file-snapshot-hash", + path: rule, + sha256: createHash("sha256").update(RULE).digest("hex"), + bytes: Buffer.byteLength(RULE), + }, + }, + { + argument: "rule_paths[1]", + observation: { + kind: "file-snapshot-hash", + path: second, + sha256: createHash("sha256").update(secondText).digest("hex"), + bytes: Buffer.byteLength(secondText), + }, + }, + ]; + expect(result.error.argumentObservations).toEqual(expectedRuleObservations); + expect(projectAnalysisError(result.error)).toMatchObject({ + details: { + argument_observations: expectedRuleObservations, + }, + }); + }); + + it("refuses a scanned file larger than max_file_bytes with required_value", async () => { + const { sample, rule, service } = await fixture("match"); + const result = await service.inspect({ + path: sample, + rule_paths: [rule], + max_file_bytes: 8, + }); + expect(result.ok).toBe(false); + if (result.ok) return; + expect(result.error).toMatchObject({ + _tag: "AnalysisResourceConstraintError", + limit: expect.objectContaining({ + parameter: "max_file_bytes", + effective_value: 8, + required_value: Buffer.byteLength(RULE), + }), + }); + const largeSampleOnly = await service.inspect({ + path: sample, + rule_paths: [rule], + max_file_bytes: Buffer.byteLength(RULE), + }); + if (SAMPLE.length > Buffer.byteLength(RULE)) { + expect(largeSampleOnly.ok).toBe(false); + } else { + const largeTarget = join(dirname(sample), "large.bin"); + await writeFile(largeTarget, Buffer.alloc(Buffer.byteLength(RULE) + 17)); + const targetResult = await service.inspect({ + path: largeTarget, + rule_paths: [rule], + max_file_bytes: Buffer.byteLength(RULE), + }); + expect(targetResult.ok).toBe(false); + if (!targetResult.ok) { + expect(targetResult.error).toMatchObject({ + _tag: "AnalysisResourceConstraintError", + limit: expect.objectContaining({ + parameter: "max_file_bytes", + effective_value: Buffer.byteLength(RULE), + required_value: Buffer.byteLength(RULE) + 17, + }), + }); + } + } + }); + + it("refuses a rule file whose rewritten relative includes exceed max_file_bytes before launching yara", async () => { + const { root, sample, args, service } = await fixture("resolve"); + const longDir = join(root, "nested-rule-directory".repeat(4)); + await mkdir(longDir, { recursive: true }); + const ruleText = + Array.from({ length: 8 }, (_, i) => `include "r${String(i)}.yar"`).join( + "\n", + ) + "\n"; + const rulePath = join(longDir, "main.yar"); + await writeFile(rulePath, ruleText); + const maxFileBytes = Buffer.byteLength(ruleText) + 32; + const result = await service.inspect({ + path: sample, + rule_paths: [rulePath], + max_file_bytes: maxFileBytes, + }); + expect(result.ok).toBe(false); + if (result.ok) return; + expect(result.error.cleanupIncomplete).toBe(false); + expect(result.error).toMatchObject({ + _tag: "AnalysisResourceConstraintError", + limit: expect.objectContaining({ + control_kind: "parameter", + parameter: "max_file_bytes", + effective_value: maxFileBytes, + }), + }); + expect(result.error.limit).not.toHaveProperty("required_value"); + await expect(readFile(args)).rejects.toMatchObject({ code: "ENOENT" }); + }); + + it("retains completed rule identity when a buffered trailing include exceeds max_file_bytes during finish", async () => { + const { root, sample, args, service } = await fixture("resolve"); + const longDir = join(root, "nested-rule-directory".repeat(3)); + await mkdir(longDir, { recursive: true }); + const trailingTail = "trailing-unterminated-include-path"; + const ruleText = `include "a.yar"\ninclude "${trailingTail}`; + const rulePath = join(longDir, "main.yar"); + await writeFile(rulePath, ruleText); + const pushedBytes = Buffer.byteLength( + `include "${longDir}/a.yar"\ninclude "`, + ); + const maxFileBytes = pushedBytes; + expect(Buffer.byteLength(ruleText)).toBeLessThanOrEqual(maxFileBytes); + expect(pushedBytes + Buffer.byteLength(trailingTail)).toBeGreaterThan( + maxFileBytes, + ); + const result = await service.inspect({ + path: sample, + rule_paths: [rulePath], + max_file_bytes: maxFileBytes, + }); + expect(result.ok).toBe(false); + if (result.ok) return; + expect(result.error.cleanupIncomplete).toBe(false); + expect(result.error).toMatchObject({ + _tag: "AnalysisResourceConstraintError", + limit: expect.objectContaining({ + control_kind: "parameter", + parameter: "max_file_bytes", + effective_value: maxFileBytes, + }), + }); + const expectedObservation = { + kind: "file-snapshot-hash", + path: rulePath, + sha256: createHash("sha256").update(ruleText).digest("hex"), + bytes: Buffer.byteLength(ruleText), + }; + expect(result.error.partialObservation).toEqual(expectedObservation); + expect(projectAnalysisError(result.error)).toMatchObject({ + details: { + partial_observation: expectedObservation, + }, + }); + await expect(readFile(args)).rejects.toMatchObject({ code: "ENOENT" }); + }); + + it("refuses matches when the scanned file changes during the scan", async () => { + const { sample, rule, service } = await fixture("mutate"); + const result = await service.inspect({ path: sample, rule_paths: [rule] }); + expect(!result.ok && result.error._tag).toBe( + "AnalysisArtifactChangedError", + ); + }); + + it("retains the scanned file's partial_observation when a rule file fails its final check after the scan", async () => { + const { root, sample, rule, service } = await fixture("mutate-rule"); + const second = join(root, "second.yar"); + await writeFile(second, "rule Second { condition: true }\n"); + const result = await service.inspect({ + path: sample, + rule_paths: [rule, second], + }); + expect(result.ok, JSON.stringify(result)).toBe(false); + if (result.ok) return; + const expectedObservation = { + kind: "file-snapshot-hash", + path: sample, + sha256: createHash("sha256").update(SAMPLE).digest("hex"), + bytes: SAMPLE.length, + }; + expect(result.error).toMatchObject({ + _tag: "AnalysisArtifactChangedError", + path: second, + partialObservation: expectedObservation, + }); + expect(projectAnalysisError(result.error)).toMatchObject({ + code: "artifact_changed", + details: { + path: second, + partial_observation: expectedObservation, + }, + }); + }); + + it("refuses paths containing line breaks", async () => { + const { root, rule, service } = await fixture("match"); + const result = await service.inspect({ + path: join(root, "two\nlines.bin"), + rule_paths: [rule], + }); + expect(result.ok).toBe(false); + if (result.ok) return; + expect(result.error).toMatchObject({ + _tag: "AnalysisInputError", + issues: [expect.objectContaining({ path: ["path"] })], + }); + }); + + it("resolves a relative REA_YARA_COMMAND against cwd before launching from root", async () => { + const { command, sample, rule, args } = await fixture("match"); + const relativeCommand = relative(process.cwd(), command); + const service = createYaraMatchesService({ + ...process.env, + REA_YARA_COMMAND: relativeCommand, + YARA_STUB_MODE: "match", + YARA_STUB_ARGS: args, + }); + const result = await service.inspect({ path: sample, rule_paths: [rule] }); + expect(result.ok, JSON.stringify(result)).toBe(true); + if (!result.ok) return; + expect(JSON.parse(await readFile(args, "utf8")).cwd).toBe( + parse(sample).root, + ); + }); + + test("refuses drive-relative rooted Windows paths across drives before hashing or launching", async () => { + const launcher = vi.fn(); + const provider = new YaraMatchesProvider({ + environment: {}, + platform: "win32", + selectCommand: () => ok("C:\\tools\\yara.exe"), + launcher, + }); + const settings = { + max_matches: { + value: YARA_SETTING_BOUNDS.max_matches.default_value, + source: "default" as const, + }, + max_output_bytes: { + value: YARA_SETTING_BOUNDS.max_output_bytes.default_value, + source: "default" as const, + }, + command_timeout_ms: { + value: YARA_SETTING_BOUNDS.command_timeout_ms.default_value, + source: "default" as const, + }, + }; + const crossDriveRule = await provider.inspect({ + input: { + path: "D:\\samples\\sample.bin", + rule_paths: ["\\rules\\packers.yar"], + }, + settings, + }); + expect(crossDriveRule.ok).toBe(false); + if (!crossDriveRule.ok) { + expect(crossDriveRule.error).toMatchObject({ + _tag: "AnalysisInputError", + conformsToInputContract: true, + issues: [ + expect.objectContaining({ + path: ["rule_paths", 0], + reason: "invalid_value", + }), + ], + }); + } + const rootedTarget = await provider.inspect({ + input: { + path: "\\samples\\sample.bin", + rule_paths: ["D:\\rules\\packers.yar"], + }, + settings, + }); + expect(rootedTarget.ok).toBe(false); + if (!rootedTarget.ok) { + expect(rootedTarget.error).toMatchObject({ + _tag: "AnalysisInputError", + conformsToInputContract: true, + issues: [ + expect.objectContaining({ + path: ["path"], + reason: "invalid_value", + }), + ], + }); + } + expect(launcher).not.toHaveBeenCalled(); + }); +}); diff --git a/tests/boundary/providers/yaraRealCommand.test.ts b/tests/boundary/providers/yaraRealCommand.test.ts new file mode 100644 index 00000000000..272ef6f7bd8 --- /dev/null +++ b/tests/boundary/providers/yaraRealCommand.test.ts @@ -0,0 +1,234 @@ +import { execFileSync } from "node:child_process"; +import { createHash, randomUUID } from "node:crypto"; +import { mkdir, rm, writeFile } from "node:fs/promises"; +import { dirname, join, resolve } from "node:path"; +import { expect, it } from "vitest"; + +import { YaraMatchesService } from "../../../src/application/yara/YaraMatchesService.js"; +import { createYaraMatchesService } from "../../../src/composition/yara.js"; +import { ok } from "../../../src/domain/result.js"; +import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js"; +import { + YaraMatchesProvider, + type YaraLauncher, +} from "../../../src/yara/YaraMatchesProvider.js"; +import { yaraMatchesSchema } from "../../../src/domain/yara/yaraMatches.js"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; + +const findYara = (): string | undefined => { + if (process.platform === "win32") return undefined; + try { + const path = execFileSync("which", ["yara"], { encoding: "utf8" }).trim(); + return path === "" ? undefined : path; + } catch { + return undefined; + } +}; + +const yara = findYara(); + +const RULES = String.raw`rule Hello : tagA tagB +{ + meta: + author = "A \"q\" \\ b" + score = 42 + ok = true + strings: + $t = "hello" + $h = { 4D 5A 90 00 } + condition: + any of them +} +rule NotMatched { strings: $a = "zzzz" condition: $a } +`; + +const sampleFile = async () => { + const root = await createTestTempDirectory("rea-yara-real-"); + const sample = join(root, "sample [x].bin"); + await writeFile(sample, Buffer.from("MZ\x90\x00hello hello\n", "latin1")); + const rule = join(root, "rules.yar"); + await writeFile(rule, RULES); + return { root, sample, rule }; +}; + +it.skipIf(yara === undefined)( + "reads matches the installed yara reports", + async () => { + const { sample, rule } = await sampleFile(); + const service = createYaraMatchesService({ + ...process.env, + REA_YARA_COMMAND: yara, + }); + const result = await service.inspect({ path: sample, rule_paths: [rule] }); + expect(result.ok, JSON.stringify(result)).toBe(true); + if (!result.ok) return; + const report = yaraMatchesSchema.parse(result.value.normalized_result); + expect(report.matches).toEqual([ + { + rule: "Hello", + tags: ["tagA", "tagB"], + meta: [ + { identifier: "author", type: "string", value: 'A "q" \\ b' }, + { identifier: "score", type: "integer", value: 42 }, + { identifier: "ok", type: "boolean", value: true }, + ], + string_match_count: 3, + strings: [ + { identifier: "$t", file_offset: 4, length: 5, data: "hello" }, + { identifier: "$t", file_offset: 10, length: 5, data: "hello" }, + { identifier: "$h", file_offset: 0, length: 4, data: "4D 5A 90 00" }, + ], + }, + ]); + await service.close(); + }, +); + +it.skipIf(yara === undefined)( + "returns the installed yara's compile error as an input error", + async () => { + const { root, sample } = await sampleFile(); + const bad = join(root, "bad.yar"); + await writeFile(bad, "rule Bad { condition: nope }\n"); + const service = createYaraMatchesService({ + ...process.env, + REA_YARA_COMMAND: yara, + }); + const result = await service.inspect({ path: sample, rule_paths: [bad] }); + expect(result.ok).toBe(false); + if (result.ok) return; + expect(result.error).toMatchObject({ + _tag: "AnalysisInputError", + issues: [ + expect.objectContaining({ + path: ["rule_paths", 0], + message: expect.stringContaining('undefined identifier "nope"'), + }), + ], + }); + }, +); + +/** A rule file under a directory whose name holds a colon, as `a:b`. */ +const colonRule = async (root: string, source: string): Promise => { + const directory = join(root, `rea-yara-ns:rea-yara-split-${randomUUID()}`); + await mkdir(directory); + const rule = join(directory, "rule.yar"); + await writeFile(rule, source); + return rule; +}; + +const realService = (command: string, launcher?: YaraLauncher) => + new YaraMatchesService( + new YaraMatchesProvider({ + environment: process.env, + selectCommand: () => ok(command), + ...(launcher === undefined ? {} : { launcher }), + }), + process.env, + ); + +it.skipIf(yara === undefined)( + "compiles a rule file whose path contains a colon and maps its compile error", + async () => { + const { root, sample } = await sampleFile(); + const rule = await colonRule( + root, + 'rule ColonRule { strings: $t = "hello" condition: $t }\n', + ); + const bad = await colonRule(root, "rule Bad { condition: nope }\n"); + const service = realService(yara!); + const result = await service.inspect({ path: sample, rule_paths: [rule] }); + expect(result.ok, JSON.stringify(result)).toBe(true); + if (!result.ok) return; + const report = yaraMatchesSchema.parse(result.value.normalized_result); + expect(report.matches.map((match) => match.rule)).toEqual(["ColonRule"]); + const failed = await service.inspect({ + path: sample, + rule_paths: [rule, bad], + }); + expect(failed.ok).toBe(false); + if (failed.ok) return; + expect(failed.error).toMatchObject({ + _tag: "AnalysisInputError", + issues: [expect.objectContaining({ path: ["rule_paths", 1] })], + }); + }, +); + +it.skipIf(yara === undefined)( + "never lets the installed yara compile another file for a replaced colon rule path", + async () => { + const { root, sample } = await sampleFile(); + const rule = await colonRule(root, "rule HashedRule { condition: true }\n"); + const planted: string[] = []; + // Between hashing and launch the selected file disappears and a file + // appears where yara's NAMESPACE:FILE split of a bare path would point. + const launcher: YaraLauncher = async (spawn) => { + await rm(rule); + const split = rule.slice(rule.indexOf(":") + 1); + const decoy = resolve(spawn.cwd ?? process.cwd(), split); + try { + await mkdir(dirname(decoy)); + planted.push(dirname(decoy)); + await writeFile(decoy, "rule DecoyRule { condition: true }\n"); + } catch { + // A working directory REA chose may not be writable; nothing to plant. + } + return spawnOwnedProviderProcess(spawn); + }; + try { + const result = await realService(yara!, launcher).inspect({ + path: sample, + rule_paths: [rule], + }); + expect(result.ok, JSON.stringify(result)).toBe(true); + if (!result.ok) return; + const report = yaraMatchesSchema.parse(result.value.normalized_result); + expect(report.matches.map((match) => match.rule)).toEqual(["HashedRule"]); + expect(report.rule_files.map((file) => file.path)).toEqual([rule]); + } finally { + await Promise.all( + planted.map((path) => rm(path, { recursive: true, force: true })), + ); + } + }, +); + +it.skipIf(yara === undefined)( + "compiles a rule file with a relative include directive against its original directory", + async () => { + const { root, sample } = await sampleFile(); + const rulesDir = join(root, "rules"); + await mkdir(rulesDir); + const common = join(rulesDir, "common.yar"); + await writeFile( + common, + 'rule CommonRule { strings: $t = "hello" condition: $t }\n', + ); + const mainSource = + 'include "common.yar"\nrule MainRule { condition: CommonRule }\n'; + const mainRule = join(rulesDir, "main.yar"); + await writeFile(mainRule, mainSource); + const service = realService(yara!); + const result = await service.inspect({ + path: sample, + rule_paths: [mainRule], + }); + expect(result.ok, JSON.stringify(result)).toBe(true); + if (!result.ok) return; + const report = yaraMatchesSchema.parse(result.value.normalized_result); + expect(report.matches.map((match) => match.rule)).toEqual([ + "CommonRule", + "MainRule", + ]); + expect(report.rule_files).toEqual([ + { + path: mainRule, + sha256: createHash("sha256").update(mainSource).digest("hex"), + bytes: Buffer.byteLength(mainSource), + }, + ]); + await service.close(); + }, +); diff --git a/tests/conformance/providerCapabilityCases.ts b/tests/conformance/providerCapabilityCases.ts index d826344661d..fc071588213 100644 --- a/tests/conformance/providerCapabilityCases.ts +++ b/tests/conformance/providerCapabilityCases.ts @@ -174,4 +174,10 @@ export const PROVIDER_CAPABILITY_CONFORMANCE: Readonly< cases: ["tests/acceptance/webSourceLocationCli.test.ts"], }, windowsShortcut: { cases: ["tests/acceptance/windowsShortcutCli.test.ts"] }, + yaraMatches: { + cases: [ + "tests/acceptance/yaraMatchesCli.test.ts", + "tests/boundary/mcp/yaraMatchesMcp.test.ts", + ], + }, }; diff --git a/tests/fixtures/yara/yaraStub.ts b/tests/fixtures/yara/yaraStub.ts new file mode 100644 index 00000000000..26400b9bb8e --- /dev/null +++ b/tests/fixtures/yara/yaraStub.ts @@ -0,0 +1,142 @@ +import { writeFile } from "node:fs/promises"; +import { join } from "node:path"; + +import { YaraMatchesService } from "../../../src/application/yara/YaraMatchesService.js"; +import { ok } from "../../../src/domain/result.js"; +import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js"; +import { + YaraMatchesProvider, + type YaraLauncher, +} from "../../../src/yara/YaraMatchesProvider.js"; + +/** + * A yara stand-in. YARA_STUB_MODE selects the behavior; the last argument is + * the scanned path and the arguments before it are the options and rules. + * Rule arguments resolve as yara 4.6.0 resolves them: the whole argument, + * relative to the working directory, when that file exists, and otherwise + * the NAMESPACE:FILE split at the first colon. + */ +export const YARA_STUB = String.raw` +const fs = require("node:fs"); +const { dirname, resolve } = require("node:path"); +const args = process.argv.slice(2); +const target = args.at(-1); +const ruleArgs = args.filter((value) => value.endsWith(".yar")); +const ruleFile = (arg) => { + if (fs.existsSync(resolve(process.cwd(), arg))) return arg; + const colon = arg.indexOf(":"); + return colon === -1 ? arg : arg.slice(colon + 1); +}; +const rules = ruleArgs.map(ruleFile); +if (process.env.YARA_STUB_ARGS) fs.writeFileSync(process.env.YARA_STUB_ARGS, JSON.stringify({ args, cwd: process.cwd() })); +const collectRuleNames = (filePath) => { + const fullPath = resolve(process.cwd(), filePath); + if (!fs.existsSync(fullPath)) { + process.stderr.write("error: could not open file: " + filePath + "\n"); + process.exit(1); + } + const text = fs.readFileSync(fullPath, "utf8"); + const names = []; + for (const line of text.split(/\r?\n/)) { + const inc = /^\s*include\s+"([^"]+)"\s*$/.exec(line); + if (inc) { + const targetInc = resolve(dirname(fullPath), inc[1]); + if (!fs.existsSync(targetInc)) { + // yara 4.x print_compiler_error, rule-less form. + process.stderr.write(filePath + "(1): error: can't open include file: " + inc[1] + "\n"); + process.exit(1); + } + names.push(...collectRuleNames(targetInc)); + continue; + } + const rule = /^\s*rule\s+(\w+)/.exec(line); + if (rule) names.push(rule[1]); + } + return names; +}; +switch (process.env.YARA_STUB_MODE) { + case "resolve": + for (const file of rules) { + for (const name of collectRuleNames(file)) { + process.stdout.write(name + " [] [] " + target + "\n"); + } + } + break; + case "match": + process.stderr.write('warning: rule "Slow" in ' + rules[0] + '(2): string "$a" may slow down scanning\n'); + process.stdout.write('Packed [packer,upx] [author="Analyst",score =7] ' + target + "\n"); + process.stdout.write("0x0:4:$mz: MZ\\x90\\x00\n0x10:3:$upx: UPX\n"); + process.stdout.write("Plain [] [] " + target + "\n"); + break; + case "many": + process.stdout.write("Many [] [] " + target + "\n"); + for (let index = 0; index < 50; index += 1) + process.stdout.write("0x" + index.toString(16) + ":1:$a: A\n"); + break; + case "compile": + process.stderr.write('error: rule "Bad" in ' + rules[0] + '(3): undefined identifier "nope"\n'); + process.exit(1); + case "duplicate-string": + process.stderr.write('error: rule "Dup" in ' + rules[0] + '(4): duplicated string identifier "$a"\n'); + process.exit(1); + case "scan-error": + process.stderr.write("error scanning " + target + ": could not map file\n"); + process.exit(1); + case "garbage": + process.stdout.write("this is not yara output\n"); + break; + case "flood": + process.stdout.write("Flood [] [] " + target + "\n"); + for (let index = 0; index < 4000; index += 1) + process.stdout.write("0x0:1:$a: A\n"); + break; + case "mutate": + fs.appendFileSync(target, "changed during the scan"); + break; + case "mutate-rule": + fs.appendFileSync(resolve(process.cwd(), rules.at(-1)), "\n// edited in place\n"); + process.stdout.write("Plain [] [] " + target + "\n"); + break; + case "hang": + fs.writeFileSync(process.env.YARA_STUB_ARGS + ".pid", String(process.pid)); + setInterval(() => {}, 1000); + break; +} +`; + +export const YARA_STUB_SAMPLE = Buffer.from( + "MZ\x90\x00 synthetic UPX sample\n", + "latin1", +); +export const YARA_STUB_RULE = + 'rule Packed { strings: $mz = "MZ" condition: $mz }\n'; + +// The stand-in runs under node, so its process-table command is node rather +// than the selected path; disable argv-prefix matching as interpreter-driven +// launch scripts do. Process-group ownership is still verified. +export const interpreterLauncher: YaraLauncher = (spawn) => + spawnOwnedProviderProcess({ ...spawn, expectedCommand: null }); + +/** Write the stand-in as an executable node script named `yara-stub.cjs`. */ +export const writeYaraStub = async (root: string): Promise => { + const command = join(root, "yara-stub.cjs"); + await writeFile(command, `#!${process.execPath}\n${YARA_STUB}`, { + mode: 0o755, + }); + return command; +}; + +/** A service whose provider runs `command` through the interpreter launcher. */ +export const yaraStubService = ( + command: string, + environment: Readonly, + launcher: YaraLauncher = interpreterLauncher, +) => + new YaraMatchesService( + new YaraMatchesProvider({ + environment, + selectCommand: () => ok(command), + launcher, + }), + environment, + ); diff --git a/tests/support/providerLifecycleCoverage.ts b/tests/support/providerLifecycleCoverage.ts index c6aa471bdf7..322c1516363 100644 --- a/tests/support/providerLifecycleCoverage.ts +++ b/tests/support/providerLifecycleCoverage.ts @@ -2229,4 +2229,40 @@ export const PROVIDER_LIFECYCLE_COVERAGE: Readonly< ), }, }, + "yara.command": { + ownership: "process", + stages: { + launch: covered( + test( + "tests/boundary/providers/yaraMatchesProvider.test.ts", + "reports a missing yara command as unavailable with remediation", + ), + ), + handshake: ONE_SHOT, + operation: covered( + test( + "tests/boundary/providers/yaraMatchesProvider.test.ts", + "binds matches to the file and rule digests and passes argv without a shell", + ), + ), + cancel: covered( + test( + "tests/boundary/providers/yaraMatchesProvider.test.ts", + "cancels a running scan and leaves nothing to clean up", + ), + ), + cleanup: covered( + test( + "tests/boundary/providers/yaraMatchesProvider.test.ts", + "retains a failed process cleanup and retries it before the next scan", + ), + ), + retry: covered( + test( + "tests/boundary/providers/yaraMatchesProvider.test.ts", + "retains a failed process cleanup and retries it before the next scan", + ), + ), + }, + }, };