mirror of
https://github.com/morluto/rea.git
synced 2026-11-29 01:46:39 +00:00
feat(yara): scan an admitted artifact with caller-supplied YARA rules (#14688)
* feat(yara): scan an admitted artifact with caller-supplied YARA rules Add inspect_yara_matches (CLI inspect-yara-matches), which runs the installed yara command (REA_YARA_COMMAND or yara on PATH) with caller-supplied rule files against one local file. The result lists matching rules with tags, typed metadata and string match offsets, bound to the SHA-256 of the scanned file and of each rule file. yara is launched with an argument list under owned process supervision. Its stdout is parsed as it streams, and the scanned file is re-verified after the scan. command_timeout_ms, max_output_bytes and max_matches are per-call arguments and runtime analysis settings with REA_YARA_* launch seeds; max_file_bytes is per call. String matches beyond max_matches are counted and coverage is partial. A rule compile error is an input error naming the rule file, and a missing yara command is reported as capability_unavailable without affecting other tools. REA bundles no rules and downloads nothing. * Address review feedback * fix(yara): keep the scanned file's observation when a rule file fails * fix(yara): require qualified Windows paths and resolve relative POSIX commands * fix(yara): stage owned snapshot, preserve CLI array bounds, and report file-size required_value * fix(yara): preserve relative includes, retain completed matches, order snapshot cleanup, and declare writesFilesystem * chore(yara): update advertised schema summary for inspect_yara_matches * fix(yara): handle regex arguments in include rewriter and retain completed matches across process cleanup * fix(yara): preserve raw include bytes and staged file identity across close * fix(yara): preserve completed rule identities and malformed-output primaries * fix(yara): bound rewritten rule staging and preserve cleanup cancellation * fix(yara): record completed rule identity before flushing rewritten includes * Address review feedback * Address review feedback * fix(skills): restore the macOS flat installer guidance this branch dropped The authored native-and-artifacts reference had lost main's macOS .pkg paragraph, so the generated Cursor plugin copy no longer matched it and the skill freshness check failed in docs, source tests and packaging. * fix(yara): classify compile errors by kind and keep unrecognized diagnostics yara 4.x prints compiler diagnostics in two forms, with and without a rule (cli/yara.c print_compiler_error). The include failure in the stub used a form yara never prints, so a real missing include was untested. Parse both forms once into severity, source, line, rule and message, classify the message by libyara's text (include, syntax, undefined, duplicate, unreadable file, other), and give one repair per kind present. Stderr lines that match no documented form are kept verbatim instead of only counted. * fix(yara): decode every meta escape yara prints and anchor diagnostic file names Meta strings: yara 4.x print_escaped_data also escapes an apostrophe and writes \a \b \v \f, so a meta value such as "author's" failed the whole scan as an unknown escape. Decode exactly the escapes yara writes, named after that function, and refuse octal forms it never writes. Diagnostics: a file name or message can contain "(N): ". Match the rule files yara was given exactly and end any other file name at the first location rather than the last. Name yara's EXIT_FAILURE. * fix(yara): keep an ambiguous diagnostic location unknown and scope duplicate advice A file name and a message can both contain "(N): ". Split an unnamed file only where one complete diagnostic remains; several splits leave the source and line null with the whole text kept, instead of shortening the file name or dropping the line to unrecognized stderr. Duplicate advice now covers string, tag and metadata identifiers within their rule, not only rule names. --------- Co-authored-by: Matt Van Horn <455140+mvanhorn@users.noreply.github.com> Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
This commit is contained in:
56 files changed
+6168
-9
No files matched your search
@@ -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)).
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)).
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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}`.
|
||||
|
||||
@@ -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:<snapshot_rule_path>... <snapshot_target_path>
|
||||
```
|
||||
|
||||
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.
|
||||
@@ -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
|
||||
|
||||
@@ -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) |
|
||||
|
||||
@@ -20,6 +20,7 @@ const MIGRATED_PROVIDER_ROOTS = new Set([
|
||||
"oci",
|
||||
"rust",
|
||||
"wasm",
|
||||
"yara",
|
||||
"captures",
|
||||
"signals",
|
||||
"android",
|
||||
|
||||
@@ -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)]),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -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",
|
||||
],
|
||||
},
|
||||
{
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"schemas": {
|
||||
"input compact": "bf69936321d1b7c7",
|
||||
"input compact": "0f8207f2279093da",
|
||||
"output compact": "b3a429110120aff1"
|
||||
},
|
||||
"patterns": {}
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"schemas": {
|
||||
"input compact": "e8a9e0c4cd423964",
|
||||
"output compact": "fc6c5d5a78a47254"
|
||||
},
|
||||
"patterns": {
|
||||
"input": ["^[^\\x00]*$"]
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"schemas": {
|
||||
"input compact": "7fa9c27aaf84456c",
|
||||
"input compact": "9d4e260b7995138e",
|
||||
"output compact": "39446aa1012006cc"
|
||||
},
|
||||
"patterns": {}
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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<YaraMatchesPort["inspect"]>(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();
|
||||
});
|
||||
@@ -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<Record<string, string | undefined>>,
|
||||
readonly settings?: AnalysisSettingsReader,
|
||||
) {}
|
||||
|
||||
close(): Promise<void> {
|
||||
return this.provider.close();
|
||||
}
|
||||
|
||||
async inspect(
|
||||
rawInput: unknown,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<Evidence, AnalysisError>> {
|
||||
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")
|
||||
);
|
||||
};
|
||||
@@ -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,
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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<NodeJS.ProcessEnv>,
|
||||
): 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",
|
||||
),
|
||||
);
|
||||
};
|
||||
@@ -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, {
|
||||
|
||||
@@ -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 ??
|
||||
|
||||
@@ -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<NodeJS.ProcessEnv>,
|
||||
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<NodeJS.ProcessEnv> = 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,
|
||||
);
|
||||
};
|
||||
@@ -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<Record<string, z.ZodType<number, string>>> =
|
||||
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,
|
||||
};
|
||||
|
||||
@@ -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<keyof YaraScanSettings, string>;
|
||||
|
||||
/**
|
||||
* 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<Record<keyof YaraScanSettings, number>>,
|
||||
environment: Readonly<Record<string, string | undefined>>,
|
||||
settings: AnalysisSettingsReader | undefined,
|
||||
): Result<YaraScanSettings, ConfigurationError> => {
|
||||
const overrides = settings?.().overrides;
|
||||
const resolved: Partial<Record<keyof YaraScanSettings, YaraSettingValue>> =
|
||||
{};
|
||||
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);
|
||||
};
|
||||
@@ -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;
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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[];
|
||||
@@ -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;
|
||||
@@ -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,
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<typeof yaraMetaSchema>;
|
||||
|
||||
/** 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<typeof yaraStringMatchSchema>;
|
||||
|
||||
/** 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<typeof yaraRuleMatchSchema>;
|
||||
|
||||
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<typeof yaraMatchesSchema>;
|
||||
export type YaraSettingSource = z.infer<typeof settingSource>;
|
||||
|
||||
/** 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;
|
||||
}
|
||||
@@ -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<void>;
|
||||
inspect(
|
||||
request: YaraScanRequest,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<YaraMatches, AnalysisError>>;
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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<OciImageLayoutService>,
|
||||
yaraMatches: ((service) => ({
|
||||
inspect_yara_matches: {
|
||||
admission: "application",
|
||||
run: (input, options) => service.inspect(input, options),
|
||||
},
|
||||
})) satisfies Bind<YaraMatchesService>,
|
||||
pythonPyc: ((service) => ({
|
||||
inspect_python_pyc: {
|
||||
admission: "application",
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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 <end of file>",
|
||||
'/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 <end of file>",
|
||||
},
|
||||
{
|
||||
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: [],
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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<Record<string, number>> = {
|
||||
'"': 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<YaraParsedMatches, YaraOutputFailure> {
|
||||
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 };
|
||||
};
|
||||
@@ -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.";
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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 `<include>[^\"]+` 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);
|
||||
},
|
||||
};
|
||||
};
|
||||
@@ -278,6 +278,8 @@ const pathRequests: readonly [string, Record<string, unknown>][] = [
|
||||
["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 }],
|
||||
|
||||
@@ -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");
|
||||
});
|
||||
@@ -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 &&
|
||||
|
||||
@@ -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<string, unknown> => ({
|
||||
...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",
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
},
|
||||
);
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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<string> => {
|
||||
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();
|
||||
},
|
||||
);
|
||||
@@ -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",
|
||||
],
|
||||
},
|
||||
};
|
||||
Vendored
+142
@@ -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<string> => {
|
||||
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<NodeJS.ProcessEnv>,
|
||||
launcher: YaraLauncher = interpreterLauncher,
|
||||
) =>
|
||||
new YaraMatchesService(
|
||||
new YaraMatchesProvider({
|
||||
environment,
|
||||
selectCommand: () => ok(command),
|
||||
launcher,
|
||||
}),
|
||||
environment,
|
||||
);
|
||||
@@ -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",
|
||||
),
|
||||
),
|
||||
},
|
||||
},
|
||||
};
|
||||
Reference in new issue
Block a user