@eagleoutice/flowr 2.16.7 → 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 (106) 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/identifier.d.ts +1 -1
  20. package/dataflow/environments/query-fn-props.d.ts +9 -3
  21. package/dataflow/environments/query-fn-props.js +13 -5
  22. package/dataflow/environments/reference-to-maybe.js +1 -6
  23. package/dataflow/fn/class-declaration.js +1 -8
  24. package/dataflow/graph/dataflowgraph-builder.d.ts +4 -4
  25. package/dataflow/graph/df-helper.d.ts +2 -0
  26. package/dataflow/graph/df-helper.js +7 -0
  27. package/dataflow/graph/graph.js +3 -10
  28. package/dataflow/graph/vertex.d.ts +1 -1
  29. package/dataflow/hooks.d.ts +1 -1
  30. package/dataflow/info.d.ts +3 -3
  31. package/dataflow/internal/linker.js +1 -1
  32. package/dataflow/internal/process/functions/call/built-in/built-in-ambient-state.d.ts +2 -2
  33. package/dataflow/internal/process/functions/call/built-in/built-in-library.d.ts +1 -1
  34. package/dataflow/internal/process/functions/call/built-in/built-in-try-catch.js +1 -7
  35. package/dataflow/processor.d.ts +1 -1
  36. package/documentation/wiki-linter.js +29 -0
  37. package/documentation/wiki-query.js +20 -1
  38. package/linter/linter-executor.js +2 -1
  39. package/linter/linter-rules.d.ts +65 -0
  40. package/linter/linter-rules.js +5 -1
  41. package/linter/rules/cmd-check/global-environment-modification.d.ts +14 -1
  42. package/linter/rules/cmd-check/global-environment-modification.js +15 -7
  43. package/linter/rules/no-leaked-credentials.d.ts +1 -0
  44. package/linter/rules/no-leaked-credentials.js +3 -3
  45. package/linter/rules/process-state-in-session.d.ts +71 -0
  46. package/linter/rules/process-state-in-session.js +267 -0
  47. package/linter/rules/secret-exfiltration.d.ts +80 -0
  48. package/linter/rules/secret-exfiltration.js +183 -0
  49. package/package.json +1 -1
  50. package/project/flowr-analyzer.d.ts +6 -0
  51. package/project/flowr-analyzer.js +4 -0
  52. package/project/plugins/file-plugins/files/flowr-namespace-file.d.ts +2 -0
  53. package/project/plugins/file-plugins/files/flowr-namespace-file.js +22 -3
  54. package/project/sigdb/decompress.d.ts +4 -0
  55. package/project/sigdb/decompress.js +60 -25
  56. package/project/sigdb/manifest.d.ts +1 -1
  57. package/project/sigdb/manifest.js +2 -5
  58. package/project/sigdb/reader.js +15 -6
  59. package/project/sigdb/sigdb-download.d.ts +3 -7
  60. package/project/sigdb/sigdb-download.js +71 -72
  61. package/queries/catalog/taint-query/taint-query-executor.d.ts +7 -0
  62. package/queries/catalog/taint-query/taint-query-executor.js +30 -0
  63. package/queries/catalog/taint-query/taint-query-format.d.ts +29 -0
  64. package/queries/catalog/taint-query/taint-query-format.js +124 -0
  65. package/queries/query.d.ts +12 -1
  66. package/queries/query.js +2 -0
  67. package/taint-analysis/builder/domain.d.ts +14 -0
  68. package/taint-analysis/builder/domain.js +69 -0
  69. package/taint-analysis/builder/report-template.d.ts +50 -0
  70. package/taint-analysis/builder/report-template.js +46 -0
  71. package/taint-analysis/builder/taint-analysis-definition.d.ts +108 -0
  72. package/taint-analysis/builder/taint-analysis-definition.js +128 -0
  73. package/taint-analysis/builder/taint-analysis.d.ts +124 -0
  74. package/taint-analysis/builder/taint-analysis.js +93 -0
  75. package/taint-analysis/builtin-index-bridge.d.ts +20 -0
  76. package/taint-analysis/builtin-index-bridge.js +48 -0
  77. package/taint-analysis/eval/eval.d.ts +1 -0
  78. package/taint-analysis/eval/eval.js +124 -0
  79. package/taint-analysis/eval/instrumentation.d.ts +59 -0
  80. package/taint-analysis/eval/instrumentation.js +124 -0
  81. package/taint-analysis/finite-domain.d.ts +41 -0
  82. package/taint-analysis/finite-domain.js +118 -0
  83. package/taint-analysis/function-categories.d.ts +31 -0
  84. package/taint-analysis/function-categories.js +61 -0
  85. package/taint-analysis/logger.d.ts +1 -0
  86. package/taint-analysis/logger.js +6 -0
  87. package/taint-analysis/predefined/determinism.d.ts +6 -0
  88. package/taint-analysis/predefined/determinism.js +14 -0
  89. package/taint-analysis/predefined/normalization.d.ts +17 -0
  90. package/taint-analysis/predefined/normalization.js +150 -0
  91. package/taint-analysis/predefined/predefined.d.ts +12 -0
  92. package/taint-analysis/predefined/predefined.js +18 -0
  93. package/taint-analysis/predefined/randomness-analysis.d.ts +6 -0
  94. package/taint-analysis/predefined/randomness-analysis.js +124 -0
  95. package/taint-analysis/predefined/secret-analysis.d.ts +77 -0
  96. package/taint-analysis/predefined/secret-analysis.js +165 -0
  97. package/taint-analysis/predefined/security-analysis.d.ts +7 -0
  98. package/taint-analysis/predefined/security-analysis.js +91 -0
  99. package/taint-analysis/taint-mapping.d.ts +86 -0
  100. package/taint-analysis/taint-mapping.js +70 -0
  101. package/taint-analysis/taint-resolve.d.ts +26 -0
  102. package/taint-analysis/taint-resolve.js +86 -0
  103. package/taint-analysis/taint-visitor.d.ts +80 -0
  104. package/taint-analysis/taint-visitor.js +82 -0
  105. package/util/flowr-version.d.ts +1 -1
  106. package/util/flowr-version.js +2 -2
@@ -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
+ }
@@ -0,0 +1,118 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FiniteDomain = void 0;
4
+ const abstract_domain_1 = require("../abstract-interpretation/domains/abstract-domain");
5
+ const assert_1 = require("../util/assert");
6
+ class FiniteDomain extends abstract_domain_1.AbstractDomain {
7
+ _config;
8
+ constructor(value, config) {
9
+ super(value);
10
+ this._config = config;
11
+ }
12
+ create(value) {
13
+ return new FiniteDomain(value, this._config);
14
+ }
15
+ top() {
16
+ return this.create(this._config.top);
17
+ }
18
+ bottom() {
19
+ return this.create(this._config.bottom);
20
+ }
21
+ isTop() {
22
+ return this.value === this._config.top;
23
+ }
24
+ isBottom() {
25
+ return this.value === this._config.bottom;
26
+ }
27
+ isValue() {
28
+ return this.value !== this._config.top && this.value !== this._config.bottom;
29
+ }
30
+ equalsValue(other) {
31
+ return this.value === other.value;
32
+ }
33
+ leqValue(other) {
34
+ return this.transitiveClosure(this.value).has(other.value);
35
+ }
36
+ joinValue(other) {
37
+ return this.findLeastUpperBound(other);
38
+ }
39
+ meetValue(other) {
40
+ return this.findGreatestLowerBound(other);
41
+ }
42
+ findLeastUpperBound(other) {
43
+ const thisUpper = this.upperClosure(this.value);
44
+ const otherUpper = this.upperClosure(other.value);
45
+ const commonUpper = new Set();
46
+ for (const element of thisUpper) {
47
+ if (otherUpper.has(element)) {
48
+ commonUpper.add(element);
49
+ }
50
+ }
51
+ let minimal;
52
+ for (const candidate of commonUpper) {
53
+ if (minimal === undefined || this.upperClosure(candidate).has(minimal)) {
54
+ minimal = candidate;
55
+ }
56
+ }
57
+ return minimal !== undefined ? this.create(minimal) : this.top();
58
+ }
59
+ findGreatestLowerBound(other) {
60
+ const commonLower = new Set();
61
+ for (const candidate of this._config.elements) {
62
+ const upper = this.upperClosure(candidate);
63
+ if (upper.has(this.value) && upper.has(other.value)) {
64
+ commonLower.add(candidate);
65
+ }
66
+ }
67
+ let maximal;
68
+ for (const candidate of commonLower) {
69
+ if (maximal === undefined || this.upperClosure(maximal).has(candidate)) {
70
+ maximal = candidate;
71
+ }
72
+ }
73
+ (0, assert_1.guard)(maximal !== undefined, 'Could not determine greatest lower bound');
74
+ return this.create(maximal);
75
+ }
76
+ /** All elements greater than or equal to the given element (including the element itself). */
77
+ upperClosure(element) {
78
+ const closure = this.transitiveClosure(element);
79
+ closure.add(element);
80
+ return closure;
81
+ }
82
+ /** All elements strictly greater than the given element. */
83
+ transitiveClosure(element) {
84
+ const visited = new Set();
85
+ const stack = [element];
86
+ while (stack.length > 0) {
87
+ const current = stack.pop();
88
+ (0, assert_1.guard)(current, 'Error in transitive lattice closure');
89
+ if (visited.has(current)) {
90
+ continue;
91
+ }
92
+ if (current !== element) {
93
+ visited.add(current);
94
+ }
95
+ for (const successor of this._config.leq.get(current) ?? []) {
96
+ stack.push(successor);
97
+ }
98
+ }
99
+ return visited;
100
+ }
101
+ stringify() {
102
+ return this.value.description ?? this.value.toString();
103
+ }
104
+ jsonify() {
105
+ return this.value.description ?? this.value.toString();
106
+ }
107
+ narrow(other) {
108
+ return this.meet(other); // Using meet for narrowing as the lattice is finite
109
+ }
110
+ widen(other) {
111
+ return this.join(other); // Using join for widening as the lattice is finite
112
+ }
113
+ abstract(_concrete) {
114
+ return this.create(this._value);
115
+ }
116
+ }
117
+ exports.FiniteDomain = FiniteDomain;
118
+ //# sourceMappingURL=finite-domain.js.map
@@ -0,0 +1,31 @@
1
+ import type { ArgProps, CallProps } from '../dataflow/environments/built-in-props';
2
+ import type { AnyAbstractDomain } from '../abstract-interpretation/domains/abstract-domain';
3
+ import type { TaintConditionFunction, TaintMapping } from './taint-mapping';
4
+ import { TaintRole } from './taint-mapping';
5
+ export type TaintArgSelector = {
6
+ /** Argument properties of the function category */
7
+ argProps: ArgProps;
8
+ /**
9
+ * How many arguments are of interest
10
+ * - ExactlyOne: The matching functions need to have exactly one argument fulfilling the {@link TaintArgSelector.argProps}
11
+ * - AtLeastOne: The matching functions should have at least one argument fulfilling the {@link TaintArgSelector.argProps}
12
+ */
13
+ argSelection: 'ExactlyOne' | 'AtLeastOne';
14
+ };
15
+ export type TaintFnCategory = {
16
+ /** Identifier of the function category, used to trace a resulting mapping back to its category */
17
+ name: string;
18
+ /** Role the functions of the category should get assigned to */
19
+ role: TaintRole;
20
+ /** Call properties of the function category */
21
+ callProps: CallProps;
22
+ /** Argument properties of the function category */
23
+ args: TaintArgSelector;
24
+ /** Handler describing the calculation of the resulting taint */
25
+ handler: TaintConditionFunction<AnyAbstractDomain>;
26
+ };
27
+ export declare const TaintFnCategory: Record<'pureAlias' | 'pureComputer' | 'pureShape', TaintFnCategory>;
28
+ /**
29
+ * Get the set of taint mappings for a given {@link TaintFnCategory}.
30
+ */
31
+ export declare function resolveCategoryToTaintMappings<Domain extends AnyAbstractDomain>(category: TaintFnCategory): TaintMapping<Domain>[];
@@ -0,0 +1,61 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TaintFnCategory = void 0;
4
+ exports.resolveCategoryToTaintMappings = resolveCategoryToTaintMappings;
5
+ const built_in_props_1 = require("../dataflow/environments/built-in-props");
6
+ const abstract_domain_1 = require("../abstract-interpretation/domains/abstract-domain");
7
+ const taint_mapping_1 = require("./taint-mapping");
8
+ const lattice_1 = require("../abstract-interpretation/domains/lattice");
9
+ const builtin_index_bridge_1 = require("./builtin-index-bridge");
10
+ exports.TaintFnCategory = {
11
+ /** Pure functions which return a single one of their arguments unchanged */
12
+ pureAlias: {
13
+ name: 'pureAlias',
14
+ role: taint_mapping_1.TaintRole.Transformer,
15
+ callProps: built_in_props_1.CallProp.Pure,
16
+ args: {
17
+ argProps: built_in_props_1.ArgProp.Alias,
18
+ argSelection: 'ExactlyOne',
19
+ },
20
+ /** Pass through of incoming taint */
21
+ handler: ([_arg], [taint]) => taint?.value
22
+ },
23
+ /** Pure functions which calculate their result on one or multiple arguments */
24
+ pureComputer: {
25
+ name: 'pureComputer',
26
+ role: taint_mapping_1.TaintRole.Transformer,
27
+ callProps: built_in_props_1.CallProp.Pure,
28
+ args: {
29
+ argProps: built_in_props_1.ArgProp.Value,
30
+ argSelection: 'AtLeastOne',
31
+ },
32
+ /** Least-upper bound of incoming taints */
33
+ handler: ([_arg], taints) => taints.length > 0 ? abstract_domain_1.AbstractDomain.joinAll(taints).value : lattice_1.Top
34
+ },
35
+ /** Pure functions which calculate their result based on the shape of input data */
36
+ pureShape: {
37
+ name: 'pureShape',
38
+ role: taint_mapping_1.TaintRole.Transformer,
39
+ callProps: built_in_props_1.CallProp.Pure,
40
+ args: {
41
+ argProps: built_in_props_1.ArgProp.Shape,
42
+ argSelection: 'AtLeastOne',
43
+ },
44
+ /** Least-upper bound of incoming taints */
45
+ handler: ([_arg], taints) => taints.length > 0 ? abstract_domain_1.AbstractDomain.joinAll(taints).value : lattice_1.Top
46
+ }
47
+ };
48
+ /**
49
+ * Get the set of taint mappings for a given {@link TaintFnCategory}.
50
+ */
51
+ function resolveCategoryToTaintMappings(category) {
52
+ const mappings = (0, builtin_index_bridge_1.taintMappingFromBuiltInIndex)(category.callProps, category.args.argProps, category.handler)
53
+ .map(m => {
54
+ return { role: category.role, category: category.name, ...m };
55
+ });
56
+ if (category.args.argSelection === 'ExactlyOne') {
57
+ return mappings.filter(m => (m.condition.argSignature?.sig.filter(([, p]) => (p & category.args.argProps) !== 0).length ?? 0) === 1);
58
+ }
59
+ return mappings;
60
+ }
61
+ //# sourceMappingURL=function-categories.js.map
@@ -0,0 +1 @@
1
+ export declare const taintLogger: import("tslog").Logger<import("tslog").ILogObj>;
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.taintLogger = void 0;
4
+ const log_1 = require("../util/log");
5
+ exports.taintLogger = log_1.log.getSubLogger({ name: 'taint-analysis' });
6
+ //# sourceMappingURL=logger.js.map
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Composite taint analysis combining security and randomness analyses.
3
+ * Tracks both security concerns (user/network/file input) and randomness properties (deterministic vs random)
4
+ * simultaneously during a single control-flow traversal.
5
+ */
6
+ export declare const determinism: import("../builder/taint-analysis-definition").CompositeTaintAnalysisDefinition<"determinism">;
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.determinism = void 0;
4
+ const taint_analysis_definition_1 = require("../builder/taint-analysis-definition");
5
+ const security_analysis_1 = require("./security-analysis");
6
+ const randomness_analysis_1 = require("./randomness-analysis");
7
+ const report_template_1 = require("../builder/report-template");
8
+ /**
9
+ * Composite taint analysis combining security and randomness analyses.
10
+ * Tracks both security concerns (user/network/file input) and randomness properties (deterministic vs random)
11
+ * simultaneously during a single control-flow traversal.
12
+ */
13
+ exports.determinism = taint_analysis_definition_1.TaintAnalysisDefinition.compose('determinism', [security_analysis_1.securityAnalysis, randomness_analysis_1.randomnessAnalysis], { report: (0, report_template_1.defaultReportTemplate)('Indeterminism flowing to sensitive functions') });
14
+ //# sourceMappingURL=determinism.js.map
@@ -0,0 +1,17 @@
1
+ import { Bottom, Top } from '../../abstract-interpretation/domains/lattice';
2
+ import { TaintAnalysisDefinition } from '../builder/taint-analysis-definition';
3
+ export declare const MinMax: unique symbol;
4
+ export declare const ZeroCentered: unique symbol;
5
+ export declare const UnitVariance: unique symbol;
6
+ export declare const ZScore: unique symbol;
7
+ export declare const normalizationDomain: import("../finite-domain").FiniteDomain<typeof Top, typeof Bottom, [typeof Top, typeof Bottom, typeof MinMax, typeof ZeroCentered, typeof UnitVariance, typeof ZScore]>;
8
+ /**
9
+ * Detects summary statistics whose result is a statically known constant because the input carries a specific
10
+ * normalization taint (e.g. the mean of zero-centered data is 0, the sd of unit-variance data is 1).
11
+ */
12
+ export declare const normalizationKnownConstant: TaintAnalysisDefinition<"normalization-constant", import("../finite-domain").FiniteDomain<typeof Top, typeof Bottom, [typeof Top, typeof Bottom, typeof MinMax, typeof ZeroCentered, typeof UnitVariance, typeof ZScore]>, import("../../abstract-interpretation/absint-inference").AbsintVisitorConfiguration>;
13
+ /**
14
+ * Detects any normalized value reaching any summary statistic, regardless of which normalization was applied
15
+ * or whether the result is a statically known constant.
16
+ */
17
+ export declare const normalizationReach: TaintAnalysisDefinition<"normalization-reach", import("../finite-domain").FiniteDomain<typeof Top, typeof Bottom, [typeof Top, typeof Bottom, typeof MinMax, typeof ZeroCentered, typeof UnitVariance, typeof ZScore]>, import("../../abstract-interpretation/absint-inference").AbsintVisitorConfiguration>;