mirror of
https://github.com/morluto/rea.git
synced 2026-11-28 15:18:49 +00:00
* 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>
194 lines
6.5 KiB
JavaScript
194 lines
6.5 KiB
JavaScript
import { readFileSync } from "node:fs";
|
|
import { isAbsolute, relative, resolve } from "node:path";
|
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
|
|
import { readImportSpecifiers } from "./import-specifiers.mjs";
|
|
import { isLayerException } from "./module-layers.mjs";
|
|
|
|
const PURE_LAYERS = new Set(["kernel", "domain", "contracts"]);
|
|
const MIGRATED_PROVIDER_ROOTS = new Set([
|
|
"sqlite",
|
|
"evm",
|
|
"go",
|
|
"il2cpp",
|
|
"model",
|
|
"gpu",
|
|
"python",
|
|
"deb",
|
|
"nuget",
|
|
"vsix",
|
|
"oci",
|
|
"rust",
|
|
"wasm",
|
|
"yara",
|
|
"captures",
|
|
"signals",
|
|
"android",
|
|
"firmware",
|
|
"ghidra",
|
|
"hopper",
|
|
"ida",
|
|
"inspector",
|
|
"javascript",
|
|
]);
|
|
const CENTRALIZED_CONSTRUCTOR_OWNER =
|
|
/^src\/(?:frida\/FridaInstrumentationManager|cutter\/CutterBridge(?:Client|Service)|gdb\/GdbSessionManager|rizin\/RizinDebugSessionManager)\.(?:js|ts)$/u;
|
|
const repositoryPath = (root, path) =>
|
|
relative(root, path).replaceAll("\\", "/");
|
|
|
|
const packageImports = new Map();
|
|
|
|
/** Read the package map once per repository root. */
|
|
const readPackageImports = (root) => {
|
|
if (!packageImports.has(root)) {
|
|
try {
|
|
const manifest = JSON.parse(
|
|
readFileSync(resolve(root, "package.json"), "utf8"),
|
|
);
|
|
packageImports.set(root, manifest.imports ?? {});
|
|
} catch (cause) {
|
|
throw new Error(
|
|
`Cannot read package imports from ${resolve(root, "package.json")}: ${cause.message}`,
|
|
{ cause },
|
|
);
|
|
}
|
|
}
|
|
return packageImports.get(root);
|
|
};
|
|
|
|
/**
|
|
* The file an exact-string package-map specifier names, as Node loads it.
|
|
* Conditional, array, pattern, undeclared and non-relative mappings are refused.
|
|
*/
|
|
export const packageImportTarget = (root, specifier) => {
|
|
const target = readPackageImports(root)[specifier];
|
|
if (typeof target !== "string" || !target.startsWith("./"))
|
|
throw new Error(
|
|
`Cannot resolve package import ${JSON.stringify(specifier)}: only exact "./" string mappings are supported; use a relative source import for conditional, array, pattern, or undeclared mappings.`,
|
|
);
|
|
return fileURLToPath(
|
|
new URL(target, pathToFileURL(resolve(root, "package.json"))),
|
|
);
|
|
};
|
|
|
|
/**
|
|
* The own source file a package-map specifier names.
|
|
*
|
|
* The map points at built output under `dist/`, so the same ownership rule is
|
|
* applied to the source file that produces it. Without this the gate silently
|
|
* accepts every `#`-prefixed import, which is the spelling the package map exists
|
|
* to encourage.
|
|
*/
|
|
const packageMapTarget = (root, specifier) => {
|
|
const target = packageImportTarget(root, specifier);
|
|
const source = repositoryPath(root, target)
|
|
.replace(/^dist\//u, "src/")
|
|
.replace(/\.(?:js|mjs|cjs)$/u, ".ts");
|
|
if (!source.startsWith("src/"))
|
|
throw new Error(
|
|
`Cannot resolve package import ${JSON.stringify(specifier)} to a source owner from ${JSON.stringify(repositoryPath(root, target))}; use a relative source import for this boundary check.`,
|
|
);
|
|
return resolve(root, source);
|
|
};
|
|
|
|
const sourceTarget = (root, file, specifier) => {
|
|
if (specifier.startsWith("file:")) return fileURLToPath(specifier);
|
|
if (specifier.startsWith("#")) return packageMapTarget(root, specifier);
|
|
if (isAbsolute(specifier)) return resolve(specifier);
|
|
return specifier.startsWith(".")
|
|
? fileURLToPath(new URL(specifier, pathToFileURL(file)))
|
|
: undefined;
|
|
};
|
|
|
|
const failedBoundary = (file, target, typeOnly) => {
|
|
if (!file.startsWith("src/") || !target.startsWith("src/")) return undefined;
|
|
const layer = file.split("/")[1];
|
|
const targetLayer = target.split("/")[1];
|
|
if (
|
|
file.startsWith("src/process/capture/") &&
|
|
(["application", "composition", "server", "cli", "main"].includes(
|
|
targetLayer,
|
|
) ||
|
|
/^src\/(?:cli|main)\./u.test(target))
|
|
)
|
|
return "process-capture";
|
|
if (
|
|
file.startsWith("src/application/javascript/") &&
|
|
/^src\/(?:artifacts\/AsarArtifactReader|resources\/DirectoryArtifactReader)\.(?:js|ts)$/u.test(
|
|
target,
|
|
)
|
|
)
|
|
return "provider-construction";
|
|
if (
|
|
(file.startsWith("src/artifacts/javascript/") ||
|
|
file.startsWith("src/artifacts/apple/") ||
|
|
file.startsWith("src/artifacts/inventory/") ||
|
|
file.startsWith("src/artifacts/extraction/") ||
|
|
/^src\/artifacts\/ArtifactHash\.(?:js|ts)$/u.test(file)) &&
|
|
(["application", "composition", "server", "cli", "main"].includes(
|
|
targetLayer,
|
|
) ||
|
|
/^src\/(?:cli|main)\./u.test(target))
|
|
)
|
|
return "artifact-acquisition";
|
|
if (PURE_LAYERS.has(layer) && !isLayerException(file, target)) {
|
|
if (
|
|
(/^src\/[^/]+\//u.test(target) && !PURE_LAYERS.has(targetLayer)) ||
|
|
/^src\/(?:cli|main)\./u.test(target)
|
|
)
|
|
return "pure-layer";
|
|
}
|
|
if (layer === "application" && targetLayer === "composition")
|
|
return "application-composition";
|
|
if (
|
|
(layer === "application" || layer === "server") &&
|
|
!typeOnly &&
|
|
CENTRALIZED_CONSTRUCTOR_OWNER.test(target)
|
|
)
|
|
return "provider-construction";
|
|
if (
|
|
(layer === "application" || layer === "server") &&
|
|
(MIGRATED_PROVIDER_ROOTS.has(targetLayer) ||
|
|
/^src\/(?:artifacts\/ArtifactProvider|dotnet\/ManagedStaticProvider|native\/NativeMacOSProvider)\.[^/]+$/u.test(
|
|
target,
|
|
) ||
|
|
/^src\/browser\/[^/]*Provider\.[^/]+$/u.test(target))
|
|
)
|
|
return "provider-construction";
|
|
return undefined;
|
|
};
|
|
|
|
/** Each own-source import of a file, resolved to its repository path. */
|
|
export const resolveModuleImports = (file, source, root) => {
|
|
const absoluteFile = resolve(root, file);
|
|
const importer = repositoryPath(root, absoluteFile);
|
|
const imports = [];
|
|
for (const { specifier, line, typeOnly } of readImportSpecifiers(source)) {
|
|
const resolved = sourceTarget(root, absoluteFile, specifier);
|
|
if (resolved === undefined) continue;
|
|
imports.push({
|
|
file: importer,
|
|
line,
|
|
specifier,
|
|
typeOnly,
|
|
target: repositoryPath(root, resolved),
|
|
});
|
|
}
|
|
return imports;
|
|
};
|
|
|
|
/** Check resolved source ownership, including type imports and reexports. */
|
|
export const inspectModuleBoundaries = (file, source, root) =>
|
|
inspectResolvedModuleBoundaries(resolveModuleImports(file, source, root));
|
|
|
|
/** Check already resolved imports, as returned by resolveModuleImports. */
|
|
export const inspectResolvedModuleBoundaries = (imports) => {
|
|
const violations = [];
|
|
for (const { file, line, specifier, typeOnly, target } of imports) {
|
|
const boundary = failedBoundary(file, target, typeOnly);
|
|
if (boundary !== undefined)
|
|
violations.push({ file, line, specifier, target, boundary });
|
|
}
|
|
return violations;
|
|
};
|