|
| 1 | +# @WHO: scripts/rust_command_taint.py |
| 2 | +# @WHAT: Regex-based taint detection for #[tauri::command] parameters flowing to dangerous sinks |
| 3 | +# @PART: engine |
| 4 | +# @ENTRY: scan_workspace() |
| 5 | +"""Rust `#[tauri::command]` parameter-to-sink taint detection (issue #240, MVP). |
| 6 | +
|
| 7 | +`ast_taint_engine.py` only supports Python/JS/TS/TSX — Rust has zero taint |
| 8 | +coverage. Full cross-language taint (tracing a value from a TypeScript |
| 9 | +`invoke("cmd", {...})` call across the IPC boundary into the matching Rust |
| 10 | +`#[tauri::command]` function) is out of scope for this MVP — see |
| 11 | +docs/design/0240-tauri-command-param-taint.md for why. |
| 12 | +
|
| 13 | +What this DOES cover: every parameter of a `#[tauri::command]`-annotated |
| 14 | +function is untrusted input by construction (that's exactly how Tauri's IPC |
| 15 | +dispatch delivers frontend data to Rust) — no cross-language tracing needed |
| 16 | +to establish that. From there this is intra-procedural taint: does a |
| 17 | +parameter flow into a dangerous sink within the same function body. |
| 18 | +
|
| 19 | +This is regex-based, not a full tree-sitter AST walker (consistent with |
| 20 | +several other CodeLens engines, e.g. regexaudit_engine.py) — an explicit, |
| 21 | +documented trade-off. False negatives are possible on parameters sanitized |
| 22 | +in ways the regex can't see; there is no sanitizer allowlist in this MVP. |
| 23 | +""" |
| 24 | + |
| 25 | +import os |
| 26 | +import re |
| 27 | +from typing import Any, Dict, List |
| 28 | + |
| 29 | +from utils import DEFAULT_IGNORE_DIRS, should_ignore_dir, logger |
| 30 | + |
| 31 | + |
| 32 | +_COMMAND_ATTR_RE = re.compile( |
| 33 | + r"#\[\s*tauri::command\s*(?:\([^)]*\))?\s*\]\s*" |
| 34 | + r"(?:pub\s+)?(?:async\s+)?fn\s+(\w+)\s*\(([^)]*)\)", |
| 35 | + re.MULTILINE, |
| 36 | +) |
| 37 | + |
| 38 | +# Parameter name from a Rust fn signature: `name: Type` or `mut name: Type`. |
| 39 | +_PARAM_NAME_RE = re.compile(r"(?:mut\s+)?(\w+)\s*:") |
| 40 | + |
| 41 | +# High-confidence Rust sinks. Each maps to (rule_id, cwe, human message). |
| 42 | +_SINKS: List[Dict[str, str]] = [ |
| 43 | + { |
| 44 | + "pattern": r"Command::new\s*\(", |
| 45 | + "rule_id": "rust-command-injection", |
| 46 | + "cwe": "CWE-78", |
| 47 | + "sink": "Command::new", |
| 48 | + "message": "Tauri command parameter reaches Command::new() — potential command injection", |
| 49 | + }, |
| 50 | + { |
| 51 | + "pattern": r"std::process::Command::new\s*\(", |
| 52 | + "rule_id": "rust-command-injection", |
| 53 | + "cwe": "CWE-78", |
| 54 | + "sink": "std::process::Command::new", |
| 55 | + "message": "Tauri command parameter reaches std::process::Command::new() — potential command injection", |
| 56 | + }, |
| 57 | + { |
| 58 | + "pattern": r"std::fs::(read|write|remove_file|remove_dir|remove_dir_all|create_dir|create_dir_all|copy|rename)\s*\(", |
| 59 | + "rule_id": "rust-path-traversal", |
| 60 | + "cwe": "CWE-22", |
| 61 | + "sink": "std::fs", |
| 62 | + "message": "Tauri command parameter reaches a std::fs path operation — potential path traversal", |
| 63 | + }, |
| 64 | +] |
| 65 | + |
| 66 | + |
| 67 | +def _find_function_body(source: str, start: int) -> str: |
| 68 | + """Return the brace-matched body of the function starting at ``start`` |
| 69 | + (the index of the opening `fn` match). Returns "" if unbalanced.""" |
| 70 | + brace_start = source.find("{", start) |
| 71 | + if brace_start == -1: |
| 72 | + return "" |
| 73 | + depth = 0 |
| 74 | + for i in range(brace_start, len(source)): |
| 75 | + if source[i] == "{": |
| 76 | + depth += 1 |
| 77 | + elif source[i] == "}": |
| 78 | + depth -= 1 |
| 79 | + if depth == 0: |
| 80 | + return source[brace_start:i + 1] |
| 81 | + return source[brace_start:] |
| 82 | + |
| 83 | + |
| 84 | +def _scan_file(file_path: str, rel_path: str) -> List[Dict[str, Any]]: |
| 85 | + findings: List[Dict[str, Any]] = [] |
| 86 | + try: |
| 87 | + with open(file_path, "r", encoding="utf-8", errors="ignore") as f: |
| 88 | + source = f.read() |
| 89 | + except (IOError, OSError): |
| 90 | + return findings |
| 91 | + |
| 92 | + for match in _COMMAND_ATTR_RE.finditer(source): |
| 93 | + fn_name = match.group(1) |
| 94 | + params_raw = match.group(2) |
| 95 | + params = [ |
| 96 | + m.group(1) for m in _PARAM_NAME_RE.finditer(params_raw) |
| 97 | + if m.group(1) not in ("self",) |
| 98 | + ] |
| 99 | + if not params: |
| 100 | + continue |
| 101 | + |
| 102 | + body = _find_function_body(source, match.end()) |
| 103 | + if not body: |
| 104 | + continue |
| 105 | + |
| 106 | + body_start_line = source[:match.end()].count("\n") + 1 |
| 107 | + |
| 108 | + for line_offset, line in enumerate(body.split("\n")): |
| 109 | + for sink in _SINKS: |
| 110 | + if not re.search(sink["pattern"], line): |
| 111 | + continue |
| 112 | + for param in params: |
| 113 | + # Direct usage of the parameter name as/near an argument |
| 114 | + # on the same line as the sink call. |
| 115 | + if re.search(rf"\b{re.escape(param)}\b", line): |
| 116 | + findings.append({ |
| 117 | + "rule_id": sink["rule_id"], |
| 118 | + "rule_name": "Tauri command parameter taint", |
| 119 | + "severity": "high", |
| 120 | + "cwe": sink["cwe"], |
| 121 | + "message": ( |
| 122 | + f"{sink['message']} in #[tauri::command] fn " |
| 123 | + f"'{fn_name}' (parameter '{param}')" |
| 124 | + ), |
| 125 | + "file": rel_path, |
| 126 | + "line": body_start_line + line_offset, |
| 127 | + "source": f"tauri::command param '{param}'", |
| 128 | + "sink": sink["sink"], |
| 129 | + "tainted_variable": param, |
| 130 | + "sanitized": False, |
| 131 | + "confidence": "medium", |
| 132 | + "taint_path": ( |
| 133 | + f"#[tauri::command] fn {fn_name}({param}: ...) " |
| 134 | + f"→ {sink['sink']}" |
| 135 | + ), |
| 136 | + "engine": "rust_command_taint", |
| 137 | + }) |
| 138 | + return findings |
| 139 | + |
| 140 | + |
| 141 | +def scan_workspace(workspace: str, max_files: int = 3000) -> List[Dict[str, Any]]: |
| 142 | + """Scan all `.rs` files in ``workspace`` for tainted Tauri command |
| 143 | + parameters reaching a dangerous sink. |
| 144 | +
|
| 145 | + Returns a list of finding dicts in the same shape as |
| 146 | + ``ast_taint_engine``'s Python/JS findings (rule_id, severity, cwe, |
| 147 | + message, file, line, source, sink, tainted_variable, sanitized, |
| 148 | + confidence, taint_path) so callers can merge them into one list. |
| 149 | + """ |
| 150 | + findings: List[Dict[str, Any]] = [] |
| 151 | + workspace = os.path.abspath(workspace) |
| 152 | + files_scanned = 0 |
| 153 | + |
| 154 | + for root, dirs, filenames in os.walk(workspace): |
| 155 | + rel_root = os.path.relpath(root, workspace) |
| 156 | + if should_ignore_dir(rel_root): |
| 157 | + dirs.clear() |
| 158 | + continue |
| 159 | + dirs[:] = [d for d in dirs if d not in DEFAULT_IGNORE_DIRS and not d.startswith(".")] |
| 160 | + |
| 161 | + for filename in filenames: |
| 162 | + if not filename.endswith(".rs"): |
| 163 | + continue |
| 164 | + if files_scanned >= max_files: |
| 165 | + return findings |
| 166 | + file_path = os.path.join(root, filename) |
| 167 | + rel_path = os.path.relpath(file_path, workspace) |
| 168 | + try: |
| 169 | + findings.extend(_scan_file(file_path, rel_path)) |
| 170 | + except Exception: |
| 171 | + logger.debug(f"rust_command_taint: failed to scan {rel_path}", exc_info=True) |
| 172 | + files_scanned += 1 |
| 173 | + |
| 174 | + return findings |
0 commit comments