@eagleoutice/flowr 2.16.8 → 2.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/README.md +16 -10
  2. package/abstract-interpretation/absint-inference.d.ts +17 -1
  3. package/abstract-interpretation/absint-inference.js +118 -3
  4. package/abstract-interpretation/data-frame/arguments.d.ts +11 -1
  5. package/abstract-interpretation/data-frame/arguments.js +12 -0
  6. package/abstract-interpretation/domains/lattice.d.ts +2 -0
  7. package/abstract-interpretation/domains/lattice.js +0 -6
  8. package/abstract-interpretation/domains/multi-value-state-domain.d.ts +2 -1
  9. package/abstract-interpretation/domains/multi-value-state-domain.js +7 -3
  10. package/abstract-interpretation/domains/partial-product-domain.js +2 -1
  11. package/abstract-interpretation/domains/state-abstract-domain.d.ts +6 -3
  12. package/abstract-interpretation/domains/state-abstract-domain.js +13 -7
  13. package/abstract-interpretation/domains/state-domain.d.ts +4 -0
  14. package/config.js +1 -1
  15. package/control-flow/useless-loop.js +10 -8
  16. package/data/r-primitives.generated.d.ts +1 -0
  17. package/data/r-primitives.generated.js +9 -0
  18. package/data/sigdb/sigdb.remote.json +110 -110
  19. package/dataflow/environments/query-fn-props.d.ts +9 -3
  20. package/dataflow/environments/query-fn-props.js +13 -5
  21. package/dataflow/fn/class-declaration.js +1 -8
  22. package/dataflow/graph/df-helper.d.ts +2 -0
  23. package/dataflow/graph/df-helper.js +7 -0
  24. package/documentation/wiki-linter.js +29 -0
  25. package/documentation/wiki-query.js +20 -1
  26. package/linter/linter-executor.js +2 -1
  27. package/linter/linter-rules.d.ts +65 -0
  28. package/linter/linter-rules.js +5 -1
  29. package/linter/rules/cmd-check/global-environment-modification.d.ts +14 -1
  30. package/linter/rules/cmd-check/global-environment-modification.js +15 -7
  31. package/linter/rules/no-leaked-credentials.d.ts +1 -0
  32. package/linter/rules/no-leaked-credentials.js +3 -3
  33. package/linter/rules/process-state-in-session.d.ts +71 -0
  34. package/linter/rules/process-state-in-session.js +267 -0
  35. package/linter/rules/secret-exfiltration.d.ts +80 -0
  36. package/linter/rules/secret-exfiltration.js +183 -0
  37. package/package.json +1 -1
  38. package/project/flowr-analyzer.d.ts +6 -0
  39. package/project/flowr-analyzer.js +4 -0
  40. package/project/plugins/file-plugins/files/flowr-namespace-file.d.ts +2 -0
  41. package/project/plugins/file-plugins/files/flowr-namespace-file.js +22 -3
  42. package/project/sigdb/decompress.d.ts +4 -0
  43. package/project/sigdb/decompress.js +60 -25
  44. package/project/sigdb/manifest.d.ts +1 -1
  45. package/project/sigdb/manifest.js +2 -5
  46. package/project/sigdb/reader.js +15 -6
  47. package/project/sigdb/sigdb-download.d.ts +3 -7
  48. package/project/sigdb/sigdb-download.js +71 -72
  49. package/queries/catalog/taint-query/taint-query-executor.d.ts +7 -0
  50. package/queries/catalog/taint-query/taint-query-executor.js +30 -0
  51. package/queries/catalog/taint-query/taint-query-format.d.ts +29 -0
  52. package/queries/catalog/taint-query/taint-query-format.js +124 -0
  53. package/queries/query.d.ts +12 -1
  54. package/queries/query.js +2 -0
  55. package/taint-analysis/builder/domain.d.ts +14 -0
  56. package/taint-analysis/builder/domain.js +69 -0
  57. package/taint-analysis/builder/report-template.d.ts +50 -0
  58. package/taint-analysis/builder/report-template.js +46 -0
  59. package/taint-analysis/builder/taint-analysis-definition.d.ts +108 -0
  60. package/taint-analysis/builder/taint-analysis-definition.js +128 -0
  61. package/taint-analysis/builder/taint-analysis.d.ts +124 -0
  62. package/taint-analysis/builder/taint-analysis.js +93 -0
  63. package/taint-analysis/builtin-index-bridge.d.ts +20 -0
  64. package/taint-analysis/builtin-index-bridge.js +48 -0
  65. package/taint-analysis/eval/eval.d.ts +1 -0
  66. package/taint-analysis/eval/eval.js +124 -0
  67. package/taint-analysis/eval/instrumentation.d.ts +59 -0
  68. package/taint-analysis/eval/instrumentation.js +124 -0
  69. package/taint-analysis/finite-domain.d.ts +41 -0
  70. package/taint-analysis/finite-domain.js +118 -0
  71. package/taint-analysis/function-categories.d.ts +31 -0
  72. package/taint-analysis/function-categories.js +61 -0
  73. package/taint-analysis/logger.d.ts +1 -0
  74. package/taint-analysis/logger.js +6 -0
  75. package/taint-analysis/predefined/determinism.d.ts +6 -0
  76. package/taint-analysis/predefined/determinism.js +14 -0
  77. package/taint-analysis/predefined/normalization.d.ts +17 -0
  78. package/taint-analysis/predefined/normalization.js +150 -0
  79. package/taint-analysis/predefined/predefined.d.ts +12 -0
  80. package/taint-analysis/predefined/predefined.js +18 -0
  81. package/taint-analysis/predefined/randomness-analysis.d.ts +6 -0
  82. package/taint-analysis/predefined/randomness-analysis.js +124 -0
  83. package/taint-analysis/predefined/secret-analysis.d.ts +77 -0
  84. package/taint-analysis/predefined/secret-analysis.js +165 -0
  85. package/taint-analysis/predefined/security-analysis.d.ts +7 -0
  86. package/taint-analysis/predefined/security-analysis.js +91 -0
  87. package/taint-analysis/taint-mapping.d.ts +86 -0
  88. package/taint-analysis/taint-mapping.js +70 -0
  89. package/taint-analysis/taint-resolve.d.ts +26 -0
  90. package/taint-analysis/taint-resolve.js +86 -0
  91. package/taint-analysis/taint-visitor.d.ts +80 -0
  92. package/taint-analysis/taint-visitor.js +82 -0
  93. package/util/flowr-version.d.ts +1 -1
  94. package/util/flowr-version.js +2 -2
@@ -0,0 +1,124 @@
1
+ import type { ReadonlyFlowrAnalysisProvider } from '../../project/flowr-analyzer';
2
+ import type { CompositeTaintAnalysisDefinition, TaintAnalysisDefinition } from './taint-analysis-definition';
3
+ import type { AnyPredefinedTaintAnalysisName } from '../predefined/predefined';
4
+ import type { StateAbstractDomain } from '../../abstract-interpretation/domains/state-abstract-domain';
5
+ import type { AnyAbstractDomain } from '../../abstract-interpretation/domains/abstract-domain';
6
+ import type { ArgTaintProjector, TaintCallNode } from '../taint-visitor';
7
+ import type { DataflowGraph } from '../../dataflow/graph/graph';
8
+ import type { DataflowGraphVertexFunctionCall } from '../../dataflow/graph/vertex';
9
+ import type { ReadOnlyFlowrAnalyzerContext } from '../../project/context/flowr-analyzer-context';
10
+ import type { NodeId } from '../../r-bridge/lang-4.x/ast/model/processing/node-id';
11
+ import { SourceLocation } from '../../util/range';
12
+ import type { TaintConditionFunction, TaintRole } from '../taint-mapping';
13
+ import type { TaintFnCategory } from '../function-categories';
14
+ /**
15
+ * Information passed to a {@link FnCallHook} for each function call visited during taint analysis.
16
+ */
17
+ export interface FnCallHookInfo {
18
+ /** The name of the taint analysis */
19
+ name: string;
20
+ /** The role of the matched mapping (source/propagator/sink), or `undefined` for unmapped calls */
21
+ role: TaintRole | undefined;
22
+ /** Name of the {@link TaintFnCategory} the matched mapping stems from, or `undefined` if it was defined manually */
23
+ category?: string;
24
+ /** The AST node representing the function call */
25
+ node: TaintCallNode;
26
+ /** Whether the function call had an explicit mapping */
27
+ wasMapped: boolean;
28
+ /** The abstract domain value at this point (the outgoing/resolved taint) */
29
+ value: AnyAbstractDomain;
30
+ /** Resolves the incoming taint of any argument node at this call, regardless of mapping rules */
31
+ projectArg: ArgTaintProjector;
32
+ /** The data flow graph vertex of the function call */
33
+ call: DataflowGraphVertexFunctionCall;
34
+ /** The data flow graph (e.g. for resolving the call's arguments) */
35
+ dfg: DataflowGraph;
36
+ /** The analysis context (e.g. for resolving argument values) */
37
+ ctx: ReadOnlyFlowrAnalyzerContext;
38
+ }
39
+ /**
40
+ * Callback hook invoked when a function call is visited during taint analysis.
41
+ */
42
+ export type FnCallHook = (info: FnCallHookInfo) => void;
43
+ /**
44
+ * A single finding produced by a taint analysis, i.e. an AST node whose inferred taint reached Bottom (e.g. a sink call).
45
+ */
46
+ export interface TaintFinding {
47
+ /** The AST node ID that reached Bottom */
48
+ nodeId: NodeId;
49
+ /** The source location of the AST node, if it could be resolved */
50
+ loc?: SourceLocation;
51
+ /** The rendered report message for this finding, set only when the analysis uses a per-finding {@link ReportTemplate} */
52
+ msg?: string;
53
+ }
54
+ /**
55
+ * Result of running a taint analysis, containing the final abstract domain state and any findings.
56
+ */
57
+ export interface TaintInferenceResult {
58
+ /** The final abstract domain state after running the taint analysis visitor */
59
+ domains: StateAbstractDomain<AnyAbstractDomain>;
60
+ /** The message describing the findings */
61
+ msg?: string;
62
+ /** The findings produced by the analysis, i.e. one per AST node whose inferred taint reached Bottom */
63
+ findings: TaintFinding[];
64
+ }
65
+ /**
66
+ * Builder stage of a taint analysis, before any analysis definition has been added.
67
+ * {@link RunnableTaintAnalysis.run} only becomes available once
68
+ * {@link add}, {@link addComposite}, or {@link addPredefined} has been called.
69
+ */
70
+ export interface TaintAnalysisBuilder<Defs extends readonly string[]> {
71
+ /**
72
+ * Add rules for function categories (i.e. sets of functions from {@link BuiltInIndex} fulfilling certain properties).
73
+ * These rules are applied to all added analyses.
74
+ */
75
+ on(category: TaintFnCategory, handler?: TaintConditionFunction<AnyAbstractDomain>): this;
76
+ /**
77
+ * Add a callback hook that is invoked for each function call mapping during taint analysis.
78
+ */
79
+ withHook(fnCallHook: FnCallHook): this;
80
+ /**
81
+ * Add a predefined taint analysis by name.
82
+ */
83
+ addPredefined<Name extends AnyPredefinedTaintAnalysisName>(...names: Name[]): RunnableTaintAnalysis<readonly [...Defs, Name]>;
84
+ /**
85
+ * Add a custom taint analysis definition.
86
+ */
87
+ add<Name extends string>(...defs: TaintAnalysisDefinition<Name>[]): RunnableTaintAnalysis<readonly [...Defs, Name]>;
88
+ /**
89
+ * Add a composite taint analysis that combines multiple taint analyses into a product of their lattice values.
90
+ * @see {@link TaintAnalysisDefinition.compose} to create a composite taint analysis definition.
91
+ */
92
+ addComposite<Name extends string>(...defs: CompositeTaintAnalysisDefinition<Name>[]): RunnableTaintAnalysis<readonly [...Defs, Name]>;
93
+ }
94
+ export interface RunnableTaintAnalysis<Defs extends readonly string[]> extends TaintAnalysisBuilder<Defs> {
95
+ run(analyzer?: ReadonlyFlowrAnalysisProvider): Promise<Map<Defs[number], TaintInferenceResult>>;
96
+ }
97
+ /**
98
+ * Fluent builder class for conducting taint analyses.
99
+ * Please prefer using the {@link FlowrAnalyzer.taint} method to create a taint analysis.
100
+ * Use {@link TaintAnalysis.create} to obtain an instance; {@link TaintAnalysis.run} is only reachable
101
+ * after at least one of {@link add}, {@link addComposite}, or {@link addPredefined} has been called.
102
+ */
103
+ export declare class TaintAnalysis<Defs extends readonly string[] = []> implements RunnableTaintAnalysis<Defs> {
104
+ private readonly analyzer?;
105
+ private readonly defs;
106
+ private readonly categories;
107
+ private fnCallHook;
108
+ private constructor();
109
+ /**
110
+ * Create a new taint analysis builder. {@link run} is unreachable on the result until at least
111
+ * one of {@link add}, {@link addComposite}, or {@link addPredefined} has been called on it.
112
+ */
113
+ static create<Defs extends readonly string[] = []>(analyzer?: ReadonlyFlowrAnalysisProvider): TaintAnalysisBuilder<Defs>;
114
+ on(category: TaintFnCategory, handler?: TaintConditionFunction<AnyAbstractDomain>): this;
115
+ withHook(fnCallHook: FnCallHook): this;
116
+ addPredefined<Name extends AnyPredefinedTaintAnalysisName>(...names: Name[]): RunnableTaintAnalysis<readonly [...Defs, Name]>;
117
+ add<Name extends string>(...defs: TaintAnalysisDefinition<Name>[]): RunnableTaintAnalysis<readonly [...Defs, Name]>;
118
+ addComposite<Name extends string>(...defs: CompositeTaintAnalysisDefinition<Name>[]): RunnableTaintAnalysis<readonly [...Defs, Name]>;
119
+ /**
120
+ * Run one or multiple taint analyses.
121
+ */
122
+ run(analyzer?: ReadonlyFlowrAnalysisProvider | undefined): Promise<Map<Defs[number], TaintInferenceResult>>;
123
+ private wrapFnCallHook;
124
+ }
@@ -0,0 +1,93 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TaintAnalysis = void 0;
4
+ const predefined_1 = require("../predefined/predefined");
5
+ const range_1 = require("../../util/range");
6
+ const assert_1 = require("../../util/assert");
7
+ const report_template_1 = require("./report-template");
8
+ /**
9
+ * Fluent builder class for conducting taint analyses.
10
+ * Please prefer using the {@link FlowrAnalyzer.taint} method to create a taint analysis.
11
+ * Use {@link TaintAnalysis.create} to obtain an instance; {@link TaintAnalysis.run} is only reachable
12
+ * after at least one of {@link add}, {@link addComposite}, or {@link addPredefined} has been called.
13
+ */
14
+ class TaintAnalysis {
15
+ analyzer;
16
+ defs = [];
17
+ categories = [];
18
+ fnCallHook;
19
+ constructor(analyzer) {
20
+ this.analyzer = analyzer;
21
+ }
22
+ /**
23
+ * Create a new taint analysis builder. {@link run} is unreachable on the result until at least
24
+ * one of {@link add}, {@link addComposite}, or {@link addPredefined} has been called on it.
25
+ */
26
+ static create(analyzer) {
27
+ return new TaintAnalysis(analyzer);
28
+ }
29
+ on(category, handler) {
30
+ (0, assert_1.guard)(handler || category.handler, 'No handler set for given function category');
31
+ this.categories.push({ ...category, handler: handler ?? category.handler });
32
+ return this;
33
+ }
34
+ withHook(fnCallHook) {
35
+ this.fnCallHook = fnCallHook;
36
+ return this;
37
+ }
38
+ addPredefined(...names) {
39
+ for (const name of names) {
40
+ this.defs.push(predefined_1.predefinedTaintAnalyses[name]);
41
+ }
42
+ return this;
43
+ }
44
+ add(...defs) {
45
+ this.defs.push(...defs);
46
+ return this;
47
+ }
48
+ addComposite(...defs) {
49
+ this.defs.push(...defs);
50
+ return this;
51
+ }
52
+ /**
53
+ * Run one or multiple taint analyses.
54
+ */
55
+ async run(analyzer = this.analyzer) {
56
+ (0, assert_1.guard)((0, assert_1.isNotUndefined)(analyzer), 'No analyzer has been set');
57
+ const results = new Map();
58
+ const dfg = (await analyzer.dataflow()).graph;
59
+ const ctx = analyzer.inspectContext();
60
+ for (const def of this.defs) {
61
+ const baseConfig = {
62
+ controlFlow: await analyzer.controlflow(),
63
+ ctx: ctx,
64
+ dfg: dfg,
65
+ normalizedAst: await analyzer.normalize(),
66
+ fnCallHook: this.wrapFnCallHook(this.fnCallHook, def.name, dfg, ctx),
67
+ };
68
+ const interpreter = def.createVisitor(baseConfig, this.categories);
69
+ interpreter.start();
70
+ const endState = def.resultState(interpreter);
71
+ const report = def.msg;
72
+ const idMap = baseConfig.normalizedAst.idMap;
73
+ const findings = report === undefined ? [] : endState.getBottomNodes().map(nodeId => {
74
+ const node = idMap.get(nodeId);
75
+ const loc = range_1.SourceLocation.fromNode(node);
76
+ return typeof report === 'function'
77
+ ? { nodeId, loc, msg: (0, report_template_1.renderReport)(report, (0, report_template_1.buildFindingContext)(def.name, nodeId, node, loc)) }
78
+ : { nodeId, loc };
79
+ });
80
+ // If the report message is a constant string, save it only once
81
+ const msg = typeof report === 'string' ? report : undefined;
82
+ results.set(def.name, { domains: endState, msg, findings });
83
+ }
84
+ return results;
85
+ }
86
+ wrapFnCallHook(fn, name, dfg, ctx) {
87
+ return fn
88
+ ? ({ node, value, wasMapped, projectArg, call, role, category }) => fn({ name, node, value, wasMapped, projectArg, call, dfg, ctx, role, category })
89
+ : () => { };
90
+ }
91
+ }
92
+ exports.TaintAnalysis = TaintAnalysis;
93
+ //# sourceMappingURL=taint-analysis.js.map
@@ -0,0 +1,20 @@
1
+ import type { AnyAbstractDomain } from '../abstract-interpretation/domains/abstract-domain';
2
+ import type { ArgProp, PropSelector } from '../dataflow/environments/built-in-props';
3
+ import type { TaintConditionFunction, TaintConditionMapping } from './taint-mapping';
4
+ /**
5
+ * Creates a taint mapping rule for each function that matches the given {@link PropSelector} and whose signature
6
+ * has at least one parameter fulfilling {@link ArgProp}.
7
+ * @param props - The properties the function has to fulfill
8
+ * @param argProps - The properties at least one argument has to fulfill
9
+ * @param conditionFn - The taint condition function to apply to matching function calls
10
+ */
11
+ export declare function taintMappingFromBuiltInIndex<Domain extends AnyAbstractDomain>(props: PropSelector, argProps: ArgProp, conditionFn: TaintConditionFunction<Domain>): TaintConditionMapping<Domain>[];
12
+ /**
13
+ * Like {@link taintMappingFromBuiltInIndex}, but resolves the {@link ArgProp} parameters as arguments for the {@link conditionFn}.
14
+ * I.e. their position and name are read from each function's signature instead of being hard-coded.
15
+ * @param props - The properties the function has to fulfill (all of them)
16
+ * @param argProps - The properties at least one argument has to fulfill
17
+ * @param conditionFn - The taint condition function to apply to matching function calls
18
+ * @param excluding - Drop functions that also carry any of these properties
19
+ */
20
+ export declare function argValueMappingFromBuiltInIndex<Domain extends AnyAbstractDomain>(props: PropSelector, argProps: ArgProp, conditionFn: TaintConditionFunction<Domain>, excluding?: PropSelector): TaintConditionMapping<Domain>[];
@@ -0,0 +1,48 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.taintMappingFromBuiltInIndex = taintMappingFromBuiltInIndex;
4
+ exports.argValueMappingFromBuiltInIndex = argValueMappingFromBuiltInIndex;
5
+ const query_fn_props_1 = require("../dataflow/environments/query-fn-props");
6
+ const assert_1 = require("../util/assert");
7
+ /**
8
+ * Creates a taint mapping rule for each function that matches the given {@link PropSelector} and whose signature
9
+ * has at least one parameter fulfilling {@link ArgProp}.
10
+ * @param props - The properties the function has to fulfill
11
+ * @param argProps - The properties at least one argument has to fulfill
12
+ * @param conditionFn - The taint condition function to apply to matching function calls
13
+ */
14
+ function taintMappingFromBuiltInIndex(props, argProps, conditionFn) {
15
+ const identifiers = query_fn_props_1.BuiltInIndex.default().with(props);
16
+ const mappings = identifiers.map(i => {
17
+ const sig = query_fn_props_1.BuiltInIndex.default().get(i)?.sig;
18
+ if (!sig || !sig.some(([, p]) => (p & argProps) !== 0)) {
19
+ return undefined;
20
+ }
21
+ return {
22
+ identifier: i,
23
+ condition: {
24
+ argSignature: { sig, props: argProps },
25
+ conditionFn
26
+ }
27
+ };
28
+ });
29
+ return mappings.filter(assert_1.isNotUndefined);
30
+ }
31
+ /**
32
+ * Like {@link taintMappingFromBuiltInIndex}, but resolves the {@link ArgProp} parameters as arguments for the {@link conditionFn}.
33
+ * I.e. their position and name are read from each function's signature instead of being hard-coded.
34
+ * @param props - The properties the function has to fulfill (all of them)
35
+ * @param argProps - The properties at least one argument has to fulfill
36
+ * @param conditionFn - The taint condition function to apply to matching function calls
37
+ * @param excluding - Drop functions that also carry any of these properties
38
+ */
39
+ function argValueMappingFromBuiltInIndex(props, argProps, conditionFn, excluding) {
40
+ const index = query_fn_props_1.BuiltInIndex.default();
41
+ return index.withAll(props, excluding).flatMap(identifier => {
42
+ const argValues = index.get(identifier)?.sig
43
+ ?.map(([name, p], pos) => (p & argProps) !== 0 ? { pos, name } : undefined)
44
+ .filter(assert_1.isNotUndefined);
45
+ return argValues?.length ? [{ identifier, condition: { argValues, conditionFn } }] : [];
46
+ });
47
+ }
48
+ //# sourceMappingURL=builtin-index-bridge.js.map
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,124 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ /**
7
+ * Evaluation script for flowR's taint analysis.
8
+ *
9
+ * It uses the {@link FlowrAnalyzer} API and collects the function-call
10
+ * mappings through the {@link TaintAnalysisInstrumentation} hook (`analyzer.taint().withHook(...)`).
11
+ *
12
+ * For every `.R` file found (recursively) below the given dataset directory it runs the
13
+ * configured taint analyses and writes one JSON line with the collected trace to stdout
14
+ * (progress is always logged to stderr).
15
+ *
16
+ * Usage:
17
+ * ts-node src/taint-analysis/eval/eval.ts <dataset-dir>
18
+ */
19
+ const fs_1 = __importDefault(require("fs"));
20
+ const path_1 = __importDefault(require("path"));
21
+ const flowr_analyzer_builder_1 = require("../../project/flowr-analyzer-builder");
22
+ const retriever_1 = require("../../r-bridge/retriever");
23
+ const instrumentation_1 = require("./instrumentation");
24
+ const predefined_1 = require("../predefined/predefined");
25
+ const log_1 = require("../../util/log");
26
+ const lattice_1 = require("../../abstract-interpretation/domains/lattice");
27
+ /** Recursively yield all relevant `.R` files below `dir`. */
28
+ function* findRFiles(dir) {
29
+ for (const entry of fs_1.default.readdirSync(dir, { withFileTypes: true })) {
30
+ const fullPath = path_1.default.join(dir, entry.name);
31
+ if (entry.isDirectory()) {
32
+ yield* findRFiles(fullPath);
33
+ }
34
+ else if (entry.isFile() && entry.name.endsWith('.R')) {
35
+ yield fullPath;
36
+ }
37
+ }
38
+ }
39
+ /** Collect all scripts below the dataset root, deriving source/id/script name from the path. */
40
+ function collectScripts(root) {
41
+ const paths = fs_1.default.statSync(root).isDirectory() ? findRFiles(root) : [root];
42
+ return Array.from(paths, file => {
43
+ const parts = file === root ? [path_1.default.basename(file)] : path_1.default.relative(root, file).split(path_1.default.sep);
44
+ return {
45
+ scriptName: parts.length >= 3 ? parts.slice(2).join('/') : parts[parts.length - 1],
46
+ path: file,
47
+ };
48
+ });
49
+ }
50
+ /** Convert the instrumentation's nested `Map` trace into a plain, JSON-serializable object. */
51
+ function traceToObject(trace) {
52
+ const result = {};
53
+ for (const [analysis, byFile] of trace) {
54
+ const files = {};
55
+ for (const [file, info] of byFile) {
56
+ files[file ?? '<unknown>'] = info;
57
+ }
58
+ result[analysis] = files;
59
+ }
60
+ return result;
61
+ }
62
+ function taintResultsToObject(results) {
63
+ return Object.fromEntries(results.entries().map(([name, { domains, msg, findings }]) => [name, {
64
+ domains: domains.value === lattice_1.Bottom ? domains.value.description : Object.fromEntries(domains.value.entries().map(([key, domain]) => [key, domain?.toJSON() ?? null])),
65
+ msg,
66
+ findings,
67
+ }]));
68
+ }
69
+ /** Run all configured taint analyses on a single script and return the JSON line to write. */
70
+ async function analyzeScript(run, analyzer) {
71
+ console.error(`Analyzing script ${run.scriptName}`);
72
+ const instrumentation = new instrumentation_1.TaintAnalysisInstrumentation();
73
+ const start = Date.now();
74
+ let result;
75
+ try {
76
+ // drop the previous file's requests and cached results, reusing the analyzer's parser
77
+ analyzer.reset();
78
+ analyzer.addRequest(`${retriever_1.fileProtocol}${run.path}`);
79
+ const analysis = analyzer
80
+ .taint()
81
+ .addPredefined(...predefined_1.allPredefinedTaintAnalysisNames)
82
+ .withHook(instrumentation.fnCallHook);
83
+ result = await analysis.run();
84
+ }
85
+ catch (e) {
86
+ console.error(`Taint inference for script ${run.scriptName} failed: ${e.message}`);
87
+ return JSON.stringify({ script_name: run.scriptName, infer_failed: true }) + '\n';
88
+ }
89
+ console.error(`Finished taint inference for script ${run.scriptName}`);
90
+ return JSON.stringify({
91
+ script_name: run.scriptName,
92
+ infer_time: Date.now() - start,
93
+ inferred: traceToObject(instrumentation.trace),
94
+ result: taintResultsToObject(result),
95
+ }) + '\n';
96
+ }
97
+ async function main() {
98
+ const datasetArg = process.argv[2];
99
+ if (!datasetArg) {
100
+ console.error('Usage: eval <dataset-dir>');
101
+ process.exit(1);
102
+ }
103
+ const datasetPath = path_1.default.resolve(datasetArg);
104
+ if (!fs_1.default.existsSync(datasetPath)) {
105
+ console.error(`Dataset directory or file '${datasetPath}' does not exist`);
106
+ process.exit(1);
107
+ }
108
+ log_1.log.updateSettings(l => l.settings.minLevel = 6 /* LogLevel.Fatal */);
109
+ const analyzer = await new flowr_analyzer_builder_1.FlowrAnalyzerBuilder()
110
+ .setEngine('tree-sitter')
111
+ .build();
112
+ const scripts = collectScripts(datasetPath);
113
+ console.error(`Found ${scripts.length} R script(s) in ${datasetPath}; writing results to stdout`);
114
+ try {
115
+ for (const script of scripts) {
116
+ process.stdout.write(await analyzeScript(script, analyzer));
117
+ }
118
+ }
119
+ finally {
120
+ analyzer.close();
121
+ }
122
+ }
123
+ void main();
124
+ //# sourceMappingURL=eval.js.map
@@ -0,0 +1,59 @@
1
+ import { Identifier } from '../../dataflow/environments/identifier';
2
+ import type { NodeId } from '../../r-bridge/lang-4.x/ast/model/processing/node-id';
3
+ import type { FnCallHookInfo } from '../builder/taint-analysis';
4
+ import type { ControlDependency } from '../../dataflow/info';
5
+ import type { TaintRole } from '../taint-mapping';
6
+ export interface LoggedFnCallInfo {
7
+ mappedCalls: MappedCallInfo[];
8
+ unmappedCalls: CallInfo[];
9
+ }
10
+ interface ArgInfo {
11
+ name?: string;
12
+ value?: string | number | boolean | (string | number | boolean)[];
13
+ /** The incoming taint of the argument, resolved for every argument regardless of mapping rules. */
14
+ taint?: unknown;
15
+ }
16
+ interface ControlDependencyInfo extends ControlDependency {
17
+ /** Resolved construct kind, e.g. 'if', 'for', 'while', 'repeat', '&&', '||', 'stopifnot'. */
18
+ construct: string;
19
+ }
20
+ interface CallInfo {
21
+ functionName: Identifier;
22
+ nodeId: NodeId;
23
+ line: string | undefined;
24
+ /** All arguments of the call (name, resolved value, and incoming taint). */
25
+ args: ArgInfo[];
26
+ /**
27
+ * Locally-defined call targets (present only when the call resolves purely to local functions),
28
+ */
29
+ localTargets?: NodeId[];
30
+ /** Control dependencies governing the execution of this call; absent if unconditional. */
31
+ cds?: ControlDependencyInfo[];
32
+ /** Whether the cds are exhaustive (i.e., the call executes in every branch); only set when cds are present. */
33
+ inEveryBranch?: boolean;
34
+ }
35
+ interface MappedCallInfo extends CallInfo {
36
+ taint: unknown;
37
+ /** The role of the matched mapping (source/propagator/sink). */
38
+ role?: TaintRole;
39
+ /** Name of the {@link TaintFnCategory} the matched mapping stems from; absent for manually-defined mappings. */
40
+ category?: string;
41
+ }
42
+ /**
43
+ * Trace mapping: Analysis Name -\> File Name -\> FnCall Info
44
+ */
45
+ type Trace = Map<string, Map<string | undefined, LoggedFnCallInfo>>;
46
+ /**
47
+ * Collects internal information from the taint analysis using its hook system.
48
+ * To collect all function call mappings during taint analysis,
49
+ * pass the {@link TaintAnalysisInstrumentation.fnCallHook} to {@link TaintAnalysis.withHook}.
50
+ * Get all mappings after running the taint analysis from {@link TaintAnalysisInstrumentation.trace}
51
+ */
52
+ export declare class TaintAnalysisInstrumentation {
53
+ private readonly _trace;
54
+ get trace(): Trace;
55
+ fnCallHook: ({ name, node, value, wasMapped, projectArg, call, dfg, ctx, role, category }: FnCallHookInfo) => void;
56
+ private addFile;
57
+ private evaluateArguments;
58
+ }
59
+ export {};
@@ -0,0 +1,124 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TaintAnalysisInstrumentation = void 0;
4
+ const identifier_1 = require("../../dataflow/environments/identifier");
5
+ const arguments_1 = require("../../abstract-interpretation/data-frame/arguments");
6
+ const config_1 = require("../../config");
7
+ const r_function_call_1 = require("../../r-bridge/lang-4.x/ast/model/nodes/r-function-call");
8
+ const identify_link_to_last_call_relation_1 = require("../../queries/catalog/call-context-query/identify-link-to-last-call-relation");
9
+ const info_1 = require("../../dataflow/info");
10
+ const type_1 = require("../../r-bridge/lang-4.x/ast/model/type");
11
+ const resolve_helper_1 = require("../../dataflow/environments/resolve-helper");
12
+ /**
13
+ * Collects internal information from the taint analysis using its hook system.
14
+ * To collect all function call mappings during taint analysis,
15
+ * pass the {@link TaintAnalysisInstrumentation.fnCallHook} to {@link TaintAnalysis.withHook}.
16
+ * Get all mappings after running the taint analysis from {@link TaintAnalysisInstrumentation.trace}
17
+ */
18
+ class TaintAnalysisInstrumentation {
19
+ _trace = new Map();
20
+ get trace() {
21
+ return this._trace;
22
+ }
23
+ fnCallHook = ({ name, node, value, wasMapped, projectArg, call, dfg, ctx, role, category }) => {
24
+ const fnCallInfo = this.addFile(name, node);
25
+ const localTargets = (0, identify_link_to_last_call_relation_1.satisfiesCallTargets)(call, dfg, identify_link_to_last_call_relation_1.CallTargets.OnlyLocal);
26
+ const cds = call.cds?.map(cd => resolveControlDependency(cd, dfg));
27
+ const callInfo = {
28
+ line: node.info.fullRange?.[0].toString(),
29
+ nodeId: node.info.id,
30
+ functionName: call.name,
31
+ args: this.evaluateArguments(dfg, ctx, call, projectArg),
32
+ ...(localTargets === 'no' ? {} : { localTargets }),
33
+ ...(cds?.length ? { cds, inEveryBranch: (0, info_1.happensInEveryBranch)(call.cds) } : {}),
34
+ };
35
+ if (wasMapped) {
36
+ fnCallInfo.mappedCalls.push({ ...callInfo, taint: value.toJSON(), role, ...(category !== undefined ? { category } : {}) });
37
+ }
38
+ else {
39
+ fnCallInfo.unmappedCalls.push(callInfo);
40
+ }
41
+ };
42
+ addFile(name, node) {
43
+ let byFile = this._trace.get(name);
44
+ if (!byFile) {
45
+ byFile = new Map();
46
+ this._trace.set(name, byFile);
47
+ }
48
+ const file = node.info.file;
49
+ let fnCallInfo = byFile.get(file);
50
+ if (!fnCallInfo) {
51
+ fnCallInfo = { mappedCalls: [], unmappedCalls: [] };
52
+ byFile.set(file, fnCallInfo);
53
+ }
54
+ return fnCallInfo;
55
+ }
56
+ evaluateArguments(dfg, ctx, call, projectArg) {
57
+ const resolveInfo = { graph: dfg, idMap: dfg.idMap, full: true, resolve: config_1.VariableResolve.Alias, ctx: ctx };
58
+ const args = dfg.idMap !== undefined ? (0, arguments_1.getVertexArguments)(call, dfg.idMap) : [];
59
+ return args.map(arg => {
60
+ const resolvable = arg === r_function_call_1.EmptyArgument ? undefined : arg;
61
+ const valueId = resolvable?.value?.info?.id;
62
+ return {
63
+ name: resolve_helper_1.Resolve.argument.toName(resolvable, resolveInfo),
64
+ value: resolve_helper_1.Resolve.argument.value(resolvable, resolveInfo),
65
+ taint: valueId === undefined ? undefined : projectArg(valueId)?.toJSON(),
66
+ };
67
+ });
68
+ }
69
+ }
70
+ exports.TaintAnalysisInstrumentation = TaintAnalysisInstrumentation;
71
+ function resolveControlDependency(cd, dfg) {
72
+ return {
73
+ id: cd.id,
74
+ construct: classifyControlConstruct(cd, dfg),
75
+ when: cd.when,
76
+ byIteration: cd.byIteration,
77
+ file: cd.file
78
+ };
79
+ }
80
+ /**
81
+ * Binary operators that lazily evaluate their rhs and thus act as control constructs.
82
+ * See {@link BuiltInProcName.SpecialBinOp} operators in {@link DefaultBuiltinConfig}.
83
+ */
84
+ const LazyBinaryOperators = new Set(['&&', '&', '||', '|']);
85
+ /**
86
+ * Resolves the construct that causes a control dependency. The cd id points either directly at the construct
87
+ * (`if`, loops, lazy binary operators, `source`) or at a governing expression (e.g., a `stopifnot` condition or
88
+ * a `tryCatch` block), for which the enclosing named call names the construct.
89
+ */
90
+ function classifyControlConstruct(cd, dfg) {
91
+ const node = dfg.idMap?.get(cd.id);
92
+ if (node === undefined) {
93
+ return 'unknown';
94
+ }
95
+ switch (node.type) {
96
+ case type_1.RType.IfThenElse: return 'if';
97
+ case type_1.RType.ForLoop: return 'for';
98
+ case type_1.RType.WhileLoop: return 'while';
99
+ case type_1.RType.RepeatLoop: return 'repeat';
100
+ case type_1.RType.BinaryOp:
101
+ if (LazyBinaryOperators.has(node.operator)) {
102
+ return node.operator;
103
+ }
104
+ break;
105
+ case type_1.RType.FunctionCall:
106
+ // for file-exist assumptions (e.g. `source`)
107
+ if (node.named && cd.file !== undefined) {
108
+ return identifier_1.Identifier.toString(node.functionName.content);
109
+ }
110
+ break;
111
+ }
112
+ // the cd id is a governing expression (e.g., a `stopifnot` condition or a `tryCatch` block)
113
+ // the nearest enclosing named call names the construct (intermediate nodes are skipped)
114
+ for (let parent = parentNode(node, dfg); parent !== undefined; parent = parentNode(parent, dfg)) {
115
+ if (r_function_call_1.RFunctionCall.isNamed(parent)) {
116
+ return identifier_1.Identifier.toString(parent.functionName.content);
117
+ }
118
+ }
119
+ return node.type;
120
+ }
121
+ function parentNode(node, dfg) {
122
+ return node.info.parent === undefined ? undefined : dfg.idMap?.get(node.info.parent);
123
+ }
124
+ //# sourceMappingURL=instrumentation.js.map
@@ -0,0 +1,41 @@
1
+ import { AbstractDomain } from '../abstract-interpretation/domains/abstract-domain';
2
+ import type { Bottom, Top } from '../abstract-interpretation/domains/lattice';
3
+ export type LatticeElements<Top, Bottom> = (symbol | Top | Bottom)[];
4
+ export interface FiniteLatticeConfig<Top, Bot, Elements extends LatticeElements<Top, Bot> = [Top, Bot]> {
5
+ /** The Top element of the lattice (greatest element). */
6
+ readonly top: Top | typeof Top;
7
+ /** The Bottom element of the lattice (least element). */
8
+ readonly bottom: Bot | typeof Bottom;
9
+ /** The set of all lattice elements. */
10
+ readonly elements: ReadonlySet<Elements[number]>;
11
+ /**
12
+ * The partial order defining relationships between elements.
13
+ * leq[a] contains all elements b where a ≤ b (elements greater than or equal to a)
14
+ */
15
+ readonly leq: ReadonlyMap<Elements[number], ReadonlySet<Elements[number]>>;
16
+ }
17
+ export declare class FiniteDomain<Top extends symbol, Bot extends symbol, Elements extends LatticeElements<Top, Bot>> extends AbstractDomain<Elements[number], Top, Bot, Elements[number]> {
18
+ private readonly _config;
19
+ constructor(value: Elements[number], config: FiniteLatticeConfig<Top, Bot, Elements>);
20
+ create(value: Elements[number]): this;
21
+ top(): this & AbstractDomain<Elements[number], Top, Bot, Top>;
22
+ bottom(): this & AbstractDomain<Elements[number], Top, Bot, Bot>;
23
+ isTop(): this is this & AbstractDomain<Elements[number], Top, Bot, Top>;
24
+ isBottom(): this is this & AbstractDomain<Elements[number], Top, Bot, Bot>;
25
+ isValue(): this is this & AbstractDomain<Elements[number], Top, Bot, Elements[number]>;
26
+ protected equalsValue(this: FiniteDomain<Top, Bot, Elements>, other: FiniteDomain<Top, Bot, Elements>): boolean;
27
+ protected leqValue(this: FiniteDomain<Top, Bot, Elements>, other: FiniteDomain<Top, Bot, Elements>): boolean;
28
+ protected joinValue(this: this & FiniteDomain<Top, Bot, Elements>, other: FiniteDomain<Top, Bot, Elements>): this;
29
+ protected meetValue(this: this & FiniteDomain<Top, Bot, Elements>, other: FiniteDomain<Top, Bot, Elements>): this;
30
+ private findLeastUpperBound;
31
+ private findGreatestLowerBound;
32
+ /** All elements greater than or equal to the given element (including the element itself). */
33
+ private upperClosure;
34
+ /** All elements strictly greater than the given element. */
35
+ private transitiveClosure;
36
+ protected stringify(): string;
37
+ protected jsonify(): unknown;
38
+ narrow(other: this): this;
39
+ widen(other: this): this;
40
+ abstract(_concrete: ReadonlySet<Elements[number]> | typeof Top): this;
41
+ }