@yagyeshvyas/vibeguard 1.2.2 → 1.3.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.
package/src/scanner.js CHANGED
@@ -221,13 +221,19 @@ function scanFileContent(absPath, relPath, content, tree, diag) {
221
221
  noteDegraded('taint', err);
222
222
  }
223
223
 
224
- // Python taint analysis for .py files
224
+ // Python taint analysis for .py files (advanced multi-pass engine)
225
225
  if (relPath && relPath.endsWith('.py')) {
226
226
  try {
227
- const { analyzePythonTaint } = require('./engine');
228
- for (const t of analyzePythonTaint(content, lines, relPath)) findings.push(t);
227
+ const { analyzePythonTaintAdvanced } = require('./taint-py');
228
+ for (const t of analyzePythonTaintAdvanced(content, lines, relPath)) findings.push(t);
229
229
  } catch (err) {
230
- noteDegraded('python-taint', err);
230
+ // Fallback to legacy engine
231
+ try {
232
+ const { analyzePythonTaint } = require('./engine');
233
+ for (const t of analyzePythonTaint(content, lines, relPath)) findings.push(t);
234
+ } catch (e) {
235
+ noteDegraded('python-taint', e);
236
+ }
231
237
  }
232
238
  }
233
239
 
@@ -271,6 +277,38 @@ function scanFileContent(absPath, relPath, content, tree, diag) {
271
277
  );
272
278
  }
273
279
  }
280
+
281
+ // Plugin file-level rules (v2 plugin system).
282
+ try {
283
+ const { getPluginFileRules } = require('./plugin');
284
+ const pFileRules = getPluginFileRules();
285
+ for (const rule of pFileRules) {
286
+ let hits = [];
287
+ try {
288
+ hits = rule.run(content, lines, relPath) || [];
289
+ } catch (err) {
290
+ noteDegraded(`plugin-file-rule:${rule.id || 'unknown'}`, err);
291
+ hits = [];
292
+ }
293
+ for (const h of hits) {
294
+ findings.push(
295
+ makeFinding(rule, {
296
+ file: relPath,
297
+ line: h.line,
298
+ column: h.column || 1,
299
+ snippet: h.snippet,
300
+ message: h.message,
301
+ fix: h.fix,
302
+ severity: h.severity,
303
+ confidence: h.confidence,
304
+ ruleId: h.ruleId,
305
+ title: h.title,
306
+ })
307
+ );
308
+ }
309
+ }
310
+ } catch { /* plugin file rules are best-effort */ }
311
+
274
312
  return findings;
275
313
  }
276
314
 
@@ -565,6 +603,14 @@ function scan(dir, opts = {}) {
565
603
  const config = loadConfig(root);
566
604
  rules.configure(config);
567
605
 
606
+ // Reset and load plugins early — before the file scan loop — so that
607
+ // plugin fileRules and crossFileRules are available in scanFileContent.
608
+ try {
609
+ const { loadPlugins, resetPlugins } = require('./plugin');
610
+ resetPlugins();
611
+ loadPlugins(root, config);
612
+ } catch { /* plugins are best-effort */ }
613
+
568
614
  const allFiles = walk(root, [], null);
569
615
 
570
616
  // Incremental mode: only scan files whose content changed since the last scan
@@ -665,6 +711,32 @@ function scan(dir, opts = {}) {
665
711
  );
666
712
  }
667
713
  }
714
+
715
+ // Plugin cross-file rules (v2 plugin system).
716
+ try {
717
+ const { getPluginCrossFileRules } = require('./plugin');
718
+ const pCrossRules = getPluginCrossFileRules();
719
+ for (const rule of pCrossRules) {
720
+ let hits = [];
721
+ try {
722
+ hits = rule.run(contents) || [];
723
+ } catch {
724
+ hits = [];
725
+ }
726
+ for (const h of hits) {
727
+ findings.push(
728
+ makeFinding(rule, {
729
+ file: h.file,
730
+ line: h.line,
731
+ column: h.column || 1,
732
+ snippet: h.snippet,
733
+ message: h.message,
734
+ fix: h.fix,
735
+ })
736
+ );
737
+ }
738
+ }
739
+ } catch { /* plugin cross-file rules are best-effort */ }
668
740
  } // end !incremental cross-file block
669
741
 
670
742
  findings = findings.concat(projectScan(root));
@@ -710,10 +782,9 @@ function scan(dir, opts = {}) {
710
782
  }
711
783
  findings = applyConfigFilters(findings, config);
712
784
 
713
- // Merge plugin rules
785
+ // Merge plugin line rules (file/cross-file rules already applied above)
714
786
  try {
715
- const { loadPlugins, getPluginRules } = require('./plugin');
716
- loadPlugins(root, config);
787
+ const { getPluginRules } = require('./plugin');
717
788
  const pluginRules = getPluginRules();
718
789
  if (pluginRules.length > 0) {
719
790
  const { matchAll, makeFinding } = require('./rules');
@@ -0,0 +1,222 @@
1
+ 'use strict';
2
+
3
+ /*
4
+ * VibeGuard Python Taint Analysis Engine.
5
+ *
6
+ * A multi-pass, scope-aware Python taint tracker — no external parser needed
7
+ * (pure JS, zero dependencies, 100% offline).
8
+ *
9
+ * Improvements over the legacy engine.js analyzePythonTaint:
10
+ * - Multi-hop propagation through f-strings: q = f"SELECT * FROM {name}"
11
+ * - Format string propagation: q = "SELECT * FROM %s" % name
12
+ * - .format() propagation: q = "SELECT * FROM {}".format(name)
13
+ * - String concatenation propagation: q = "prefix" + name
14
+ * - Dedent-aware: Python indentation tracks scope (function/if/for/while)
15
+ * — variables that go out of scope are cleared
16
+ * - Sanitizer recognition: int(), float(), bool(), shlex.quote(), etc.
17
+ * - Parameterized query detection (placeholder + second arg to execute)
18
+ * - Confidence: 'high' when source→sink is confirmed (multi-hop), 'medium' for single-hop
19
+ *
20
+ * Sources: request.form/args/data/json/values/cookies/headers, request.get(),
21
+ * input(), os.environ, sys.argv, flask.request.args, django request.GET/POST
22
+ *
23
+ * Sinks: cursor.execute, os.system, subprocess.run/call/Popen, eval, exec,
24
+ * open, pickle.loads, os.popen, shell=True
25
+ */
26
+
27
+ const PY_TAINT_SOURCES = [
28
+ { re: /request\.(?:form|args|data|json|values|cookies|headers)(?:\.\w+)?(?:\s*\(|\s*\[)/, name: 'request' },
29
+ { re: /request\.get\s*\(/, name: 'request.get' },
30
+ { re: /request\.POST(?:\[|\.get)/, name: 'request.POST' },
31
+ { re: /request\.GET(?:\[|\.get)/, name: 'request.GET' },
32
+ { re: /flask\.request\.(?:form|args|data|json|cookies|headers)/, name: 'flask.request' },
33
+ { re: /\binput\s*\(/, name: 'input()' },
34
+ { re: /os\.environ\.get\s*\(/, name: 'os.environ' },
35
+ { re: /\bos\.environ\s*\[/, name: 'os.environ' },
36
+ { re: /\bsys\.argv\b/, name: 'sys.argv' },
37
+ { re: /event\[(?:['"])?(?:body|queryStringParameters|headers|pathParameters)/, name: 'event' },
38
+ ];
39
+
40
+ const PY_TAINT_SINKS = [
41
+ { re: /cursor\.execute\s*\(/, name: 'cursor.execute', type: 'sql', ruleId: 'py.taint.sql-injection', cwe: 'CWE-89' },
42
+ { re: /\.execute\s*\(/, name: 'execute()', type: 'sql', ruleId: 'py.taint.sql-injection', cwe: 'CWE-89' },
43
+ { re: /os\.system\s*\(/, name: 'os.system', type: 'cmd', ruleId: 'py.taint.command-injection', cwe: 'CWE-77' },
44
+ { re: /os\.popen\s*\(/, name: 'os.popen', type: 'cmd', ruleId: 'py.taint.command-injection', cwe: 'CWE-77' },
45
+ { re: /subprocess\.(?:run|call|Popen)\s*\(/, name: 'subprocess', type: 'cmd', ruleId: 'py.taint.command-injection', cwe: 'CWE-77' },
46
+ { re: /subprocess\.(?:run|call|Popen)\s*\([^)]*shell\s*=\s*True/, name: 'subprocess(shell=True)', type: 'cmd', ruleId: 'py.taint.command-injection', cwe: 'CWE-77' },
47
+ { re: /\beval\s*\(/, name: 'eval()', type: 'code', ruleId: 'py.taint.code-injection', cwe: 'CWE-94' },
48
+ { re: /\bexec\s*\(/, name: 'exec()', type: 'code', ruleId: 'py.taint.code-injection', cwe: 'CWE-94' },
49
+ { re: /\bopen\s*\(/, name: 'open()', type: 'file', ruleId: 'py.taint.path-traversal', cwe: 'CWE-22' },
50
+ { re: /pickle\.loads?\s*\(/, name: 'pickle', type: 'deserialization', ruleId: 'py.taint.deserialization', cwe: 'CWE-502' },
51
+ { re: /yaml\.load\s*\(/, name: 'yaml.load', type: 'deserialization', ruleId: 'py.taint.deserialization', cwe: 'CWE-502' },
52
+ ];
53
+
54
+ const PY_SANITIZERS = [
55
+ 'int', 'float', 'bool', 'decimal.Decimal',
56
+ 'shlex.quote', 'pipes.quote', 'shlex.split',
57
+ 'html.escape', 'markupsafe.escape', 'escape', 'bleach.clean',
58
+ 'urllib.parse.quote', 'urllib.parse.quote_plus', 're.escape',
59
+ 'str', 'len',
60
+ ];
61
+
62
+ function escapeRe(s) {
63
+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
64
+ }
65
+
66
+ function extractVarName(line) {
67
+ const m = /^\s*([A-Za-z_]\w*)\s*=\s*(.+)$/.exec(line);
68
+ return m ? { name: m[1], rhs: m[2] } : null;
69
+ }
70
+
71
+ function isSanitized(rhs, varName) {
72
+ for (const san of PY_SANITIZERS) {
73
+ const sanRe = new RegExp('\\b' + escapeRe(san) + '\\s*\\([^)]*' + escapeRe(varName) + '\\b');
74
+ if (sanRe.test(rhs)) return true;
75
+ }
76
+ return false;
77
+ }
78
+
79
+ function isParameterizedSql(line) {
80
+ if (!/\.execute\s*\(/.test(line)) return false;
81
+ const hasPlaceholder = /%s|%\(|%d|\?|:\w+/.test(line);
82
+ const hasSecondArg = /\.execute\s*\([^)]*?,\s*[([{\w'"]/.test(line);
83
+ return hasPlaceholder && hasSecondArg;
84
+ }
85
+
86
+ function rhsReferencesTainted(rhs, tainted) {
87
+ for (const [varName, info] of tainted) {
88
+ const re = new RegExp('\\b' + escapeRe(varName) + '\\b');
89
+ if (re.test(rhs) && !isSanitized(rhs, varName)) return { varName, info };
90
+ }
91
+ return null;
92
+ }
93
+
94
+ // Detect f-string, format, and concat propagation
95
+ function detectPropagation(line, lhs, rhs, tainted) {
96
+ // f"SELECT ... {var}" — f-string
97
+ if (/f["']/.test(line) || /f""".*{.*}/s.test(line)) {
98
+ return rhsReferencesTainted(rhs, tainted);
99
+ }
100
+ // "SELECT ... %s" % var — format string
101
+ if (/%s/.test(rhs) && /%\s*\(?([\w.]+)\)?/.test(rhs)) {
102
+ return rhsReferencesTainted(rhs, tainted);
103
+ }
104
+ // "SELECT ... {}".format(var)
105
+ if (/\.format\s*\(/.test(rhs)) {
106
+ return rhsReferencesTainted(rhs, tainted);
107
+ }
108
+ // "prefix" + var — concatenation
109
+ if (/\+/.test(rhs)) {
110
+ return rhsReferencesTainted(rhs, tainted);
111
+ }
112
+ // Direct reference: q = var
113
+ return rhsReferencesTainted(rhs, tainted);
114
+ }
115
+
116
+ function getIndent(line) {
117
+ const m = /^(\s*)/.exec(line);
118
+ return m ? m[1].length : 0;
119
+ }
120
+
121
+ function analyzePythonTaintAdvanced(content, lines, relPath) {
122
+ const findings = [];
123
+ const tainted = new Map(); // varName -> { name (source), line, hops }
124
+ const seen = new Set(); // dedupe sink:line
125
+ const scopeStack = [{ indent: 0, vars: new Set() }]; // scope tracking
126
+
127
+ for (let i = 0; i < lines.length; i++) {
128
+ const line = lines[i];
129
+ const lineNo = i + 1;
130
+ if (line.length > 4000) continue;
131
+ const trimmed = line.trim();
132
+ if (!trimmed || trimmed.startsWith('#')) continue;
133
+
134
+ const indent = getIndent(line);
135
+
136
+ // Pop scopes when indentation decreases
137
+ while (scopeStack.length > 1 && indent < scopeStack[scopeStack.length - 1].indent) {
138
+ const popped = scopeStack.pop();
139
+ for (const v of popped.vars) {
140
+ tainted.delete(v);
141
+ }
142
+ }
143
+
144
+ // Detect function/class/def/for/while/if/try — push new scope
145
+ if (/^\s*(def |class |for |while |if |elif |else:|try:|except |with )/.test(line)) {
146
+ scopeStack.push({ indent: indent + 1, vars: new Set() });
147
+ }
148
+
149
+ // 1. Source assignment.
150
+ let matchedSource = null;
151
+ for (const src of PY_TAINT_SOURCES) {
152
+ if (src.re.test(line)) { matchedSource = src.name; break; }
153
+ }
154
+ if (matchedSource) {
155
+ const extracted = extractVarName(line);
156
+ if (extracted) {
157
+ tainted.set(extracted.name, { name: matchedSource, line: lineNo, hops: 0 });
158
+ scopeStack[scopeStack.length - 1].vars.add(extracted.name);
159
+ }
160
+ }
161
+
162
+ // 2. Propagation via assignment.
163
+ if (!matchedSource) {
164
+ const extracted = extractVarName(line);
165
+ if (extracted) {
166
+ const lhs = extracted.name;
167
+ const rhs = extracted.rhs;
168
+ const ref = detectPropagation(line, lhs, rhs, tainted);
169
+ if (ref) {
170
+ tainted.set(lhs, { name: ref.info.name, line: ref.info.line, hops: ref.info.hops + 1 });
171
+ scopeStack[scopeStack.length - 1].vars.add(lhs);
172
+ } else if (tainted.has(lhs)) {
173
+ // Reassigned to clean value — clear taint
174
+ tainted.delete(lhs);
175
+ }
176
+ }
177
+ }
178
+
179
+ // 3. Sinks.
180
+ for (const sink of PY_TAINT_SINKS) {
181
+ if (!sink.re.test(line)) continue;
182
+ for (const [tv, info] of tainted) {
183
+ const re = new RegExp('\\b' + escapeRe(tv) + '\\b');
184
+ if (!re.test(line)) continue;
185
+ if (sink.type === 'sql' && isParameterizedSql(line)) continue;
186
+ if (isSanitized(line, tv)) continue;
187
+ const key = sink.ruleId + ':' + lineNo;
188
+ if (seen.has(key)) break;
189
+ seen.add(key);
190
+ findings.push({
191
+ ruleId: sink.ruleId,
192
+ file: relPath,
193
+ line: lineNo,
194
+ column: 1,
195
+ severity: sink.type === 'code' || sink.type === 'cmd' ? 'critical' : 'high',
196
+ confidence: info.hops > 0 ? 'high' : 'medium',
197
+ title: `Python taint: ${info.name} → ${sink.name}`,
198
+ snippet: trimmed.slice(0, 120),
199
+ message: `User input (${info.name} at line ${info.line}) flows to ${sink.name} (line ${lineNo}) via ${info.hops + 1} hop(s) without sanitization.`,
200
+ fix: sink.type === 'sql' ? 'Use parameterized queries with bound parameters.' :
201
+ sink.type === 'cmd' ? 'Use shlex.quote() or pass args as a list (shell=False).' :
202
+ sink.type === 'code' ? 'Remove eval/exec on dynamic input. Use ast.literal_eval or explicit dispatch.' :
203
+ sink.type === 'file' ? 'Sanitize with os.path.basename(), resolve against a fixed base, reject escapes.' :
204
+ sink.type === 'deserialization' ? 'Use json.loads instead of pickle/yaml.load, or validate input first.' :
205
+ 'Sanitize or validate the input before use.',
206
+ owasp: 'A03:2025 Injection',
207
+ cwe: sink.cwe,
208
+ });
209
+ break;
210
+ }
211
+ }
212
+ }
213
+
214
+ return findings;
215
+ }
216
+
217
+ module.exports = {
218
+ analyzePythonTaintAdvanced,
219
+ PY_TAINT_SOURCES,
220
+ PY_TAINT_SINKS,
221
+ PY_SANITIZERS,
222
+ };