from __future__ import annotations import ast from dataclasses import dataclass from src.rules import get_rule from src.schemas import ChangeSet, Finding, UnknownItem from src.taint import ( PASSWORD_NAMES, TaintEnv, apply_assign, call_name, expr_taint, is_concat_or_format, is_constant_str, keyword_true, name_of, seed_function_params, ) SQL_SINKS = {"execute", "executemany", "executescript", "text"} CMD_SINKS = {"os.system", "os.popen", "system", "popen"} SUBPROCESS = {"subprocess.run", "subprocess.call", "subprocess.Popen", "subprocess.check_output", "subprocess.check_call"} PATH_SINKS = {"open", "Path", "pathlib.Path", "send_file"} DESER_SINKS = {"pickle.loads", "pickle.load", "marshal.loads", "yaml.load"} SAFE_YAML = {"SafeLoader", "CSafeLoader"} SSRF_SINKS = {"urlopen", "urllib.request.urlopen", "urllib.urlopen", "requests.get", "requests.post", "requests.request", "httpx.get", "httpx.post"} XSS_SINKS = {"Markup", "markupsafe.Markup"} WEAK_HASH = {"hashlib.md5", "hashlib.sha1", "md5", "sha1"} @dataclass class ScanHit: rule_id: str path: str start_line: int end_line: int function: str snippet: str taint: str missing: list[str] node: ast.AST def _snippet(source: str, lineno: int, end: int) -> str: rows = source.splitlines() start = max(1, lineno) stop = min(len(rows), max(end, start)) return "\n".join(rows[start - 1 : stop]) def _function_at(stack: list[ast.AST]) -> str: for item in reversed(stack): if isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)): return item.name return "" class RuleVisitor(ast.NodeVisitor): def __init__(self, path: str, source: str) -> None: self.path = path self.source = source self.env = TaintEnv() self.stack: list[ast.AST] = [] self.hits: list[ScanHit] = [] self.unknowns: list[UnknownItem] = [] self.defined_functions: set[str] = set() def visit(self, node: ast.AST) -> None: self.stack.append(node) try: super().visit(node) finally: self.stack.pop() def visit_FunctionDef(self, node: ast.FunctionDef) -> None: self.defined_functions.add(node.name) previous = dict(self.env.names) seed_function_params(node, self.env) self.generic_visit(node) self.env.names = previous def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None: self.defined_functions.add(node.name) previous = dict(self.env.names) seed_function_params(node, self.env) self.generic_visit(node) self.env.names = previous def visit_Assign(self, node: ast.Assign) -> None: for target in node.targets: apply_assign(target, node.value, self.env) self.generic_visit(node) def visit_AnnAssign(self, node: ast.AnnAssign) -> None: if node.value is not None: apply_assign(node.target, node.value, self.env) self.generic_visit(node) def visit_Call(self, node: ast.Call) -> None: self._inspect_call(node) self.generic_visit(node) def _inspect_call(self, node: ast.Call) -> None: name = call_name(node) short = name.split(".")[-1] if name else "" fn = _function_at(self.stack) lineno = int(getattr(node, "lineno", 1) or 1) end = int(getattr(node, "end_lineno", lineno) or lineno) snippet = _snippet(self.source, lineno, end) if short in SQL_SINKS or name.endswith(".execute"): self._sql(node, lineno, end, fn, snippet) return if name in CMD_SINKS or short in {"system", "popen"}: self._cmd(node, lineno, end, fn, snippet, shell=True) return if name in SUBPROCESS or short in {"run", "Popen", "call", "check_output", "check_call"} and "subprocess" in name: self._cmd(node, lineno, end, fn, snippet, shell=keyword_true(node, "shell")) return if name in PATH_SINKS or short in PATH_SINKS: self._path(node, lineno, end, fn, snippet) return if name in DESER_SINKS or short in {"loads", "load"} and any(part in name for part in ("pickle", "marshal", "yaml")): self._deser(node, name, lineno, end, fn, snippet) return if name in SSRF_SINKS or short in {"urlopen", "get", "post"} and any(part in name for part in ("request", "httpx", "urllib")): self._ssrf(node, lineno, end, fn, snippet) return if name in XSS_SINKS or short == "Markup": self._xss(node, lineno, end, fn, snippet) return if name in WEAK_HASH or short in {"md5", "sha1"}: self._hash(node, lineno, end, fn, snippet) return if short == "Template" and keyword_true(node, "autoescape") is False: pass def _emit(self, rule_id: str, node: ast.AST, lineno: int, end: int, fn: str, snippet: str, taint: str, missing: list[str]) -> None: self.hits.append( ScanHit( rule_id=rule_id, path=self.path, start_line=lineno, end_line=end, function=fn, snippet=snippet, taint=taint, missing=missing, node=node, ) ) def _arg0(self, node: ast.Call) -> ast.AST | None: return node.args[0] if node.args else None def _sql(self, node: ast.Call, lineno: int, end: int, fn: str, snippet: str) -> None: first = self._arg0(node) if first is None: return if is_constant_str(first): return taint = expr_taint(first, self.env) missing: list[str] = [] if isinstance(first, ast.Call): missing.append(f"callee:{call_name(first) or 'unknown'}") taint = "unknown" if is_concat_or_format(first) or taint != "clean": self._emit("py-sql-concat", node, lineno, end, fn, snippet, taint, missing) def _cmd(self, node: ast.Call, lineno: int, end: int, fn: str, snippet: str, shell: bool) -> None: first = self._arg0(node) if first is None: return taint = expr_taint(first, self.env) if not shell and isinstance(first, ast.List) and taint == "clean": return if not shell and isinstance(first, ast.List) and all(is_constant_str(item) or isinstance(item, ast.Name) for item in first.elts): if taint != "tainted" and not any(is_concat_or_format(item) for item in first.elts): if not shell: return if shell or is_concat_or_format(first) or taint == "tainted": missing = [] if taint != "unknown" else [f"command:{name_of(first) or call_name(first) or 'expr'}"] self._emit("py-cmd-shell", node, lineno, end, fn, snippet, taint, missing) def _path(self, node: ast.Call, lineno: int, end: int, fn: str, snippet: str) -> None: first = self._arg0(node) if first is None: return if is_constant_str(first): return taint = expr_taint(first, self.env) if taint == "clean": return missing = [] if taint != "unknown" else [f"path:{name_of(first) or 'expr'}"] self._emit("py-path-join", node, lineno, end, fn, snippet, taint, missing) def _deser(self, node: ast.Call, name: str, lineno: int, end: int, fn: str, snippet: str) -> None: if "yaml.load" in name: loaders = [call_name(item.value) if isinstance(item.value, ast.Attribute | ast.Name | ast.Call) else name_of(item.value) for item in node.keywords if item.arg == "Loader"] if any(item.split(".")[-1] in SAFE_YAML for item in loaders if item): return first = self._arg0(node) if first is None: return if is_constant_str(first): return taint = expr_taint(first, self.env) missing = [] if taint != "unknown" else [f"payload:{name_of(first) or 'expr'}"] self._emit("py-pickle-load", node, lineno, end, fn, snippet, taint, missing) def _ssrf(self, node: ast.Call, lineno: int, end: int, fn: str, snippet: str) -> None: first = self._arg0(node) if first is None: return if is_constant_str(first): return taint = expr_taint(first, self.env) if taint == "clean": return missing = [] if taint != "unknown" else [f"url:{name_of(first) or 'expr'}"] self._emit("py-ssrf-url", node, lineno, end, fn, snippet, taint, missing) def _xss(self, node: ast.Call, lineno: int, end: int, fn: str, snippet: str) -> None: first = self._arg0(node) if first is None: return if is_constant_str(first): return taint = expr_taint(first, self.env) missing = [] if taint != "unknown" else [f"html:{name_of(first) or 'expr'}"] self._emit("py-xss-markup", node, lineno, end, fn, snippet, taint, missing) def _hash(self, node: ast.Call, lineno: int, end: int, fn: str, snippet: str) -> None: first = self._arg0(node) if first is None: return names = {fn.lower(), name_of(first).lower()} if isinstance(first, ast.Call) and first.args: names.add(name_of(first.args[0]).lower()) names.add(name_of(first.func).lower()) if isinstance(first, ast.Attribute): names.add(name_of(first.value).lower()) if not names & PASSWORD_NAMES and fn.lower() not in {"store_password", "hash_password", "set_password"}: return taint = expr_taint(first, self.env) if taint == "clean": return self._emit("py-weak-password-hash", node, lineno, end, fn, snippet, taint, []) def scan_source(path: str, source: str) -> tuple[list[ScanHit], list[UnknownItem], bool]: if not source.strip(): return [], [], True try: tree = ast.parse(source) except SyntaxError as exc: unknown = UnknownItem( code="syntax_error", locator=f"{path}:{exc.lineno or 1}", message=f"{path} is not valid Python and was not executed. Static parse failed.", path=path, ) return [], [unknown], False visitor = RuleVisitor(path, source) visitor.visit(tree) return visitor.hits, visitor.unknowns, True def hits_to_findings(hits: list[ScanHit], method: str = "ast_rules") -> list[Finding]: findings: list[Finding] = [] for index, hit in enumerate(hits, start=1): rule = get_rule(hit.rule_id) locator = f"{hit.path}:{hit.start_line}" findings.append( Finding( finding_id=f"F{index:03d}-{rule.family}", rule_id=rule.rule_id, family=rule.family, cwe=rule.cwe, severity=rule.severity, path=hit.path, start_line=hit.start_line, end_line=hit.end_line, function=hit.function, snippet=hit.snippet, missing_context=hit.missing, method=method, evidence_locator=locator, summary=rule.message, references=rule.references, ) ) return findings def scan_changeset(change: ChangeSet) -> tuple[list[Finding], list[UnknownItem]]: hits: list[ScanHit] = [] unknowns: list[UnknownItem] = [] for item in change.files: if not item.path.endswith(".py"): continue source = item.after if item.after.strip() else item.before file_hits, file_unknowns, _ok = scan_source(item.path, source) if item.added_lines: file_hits = [hit for hit in file_hits if _overlaps_change(hit, item.added_lines)] hits.extend(file_hits) unknowns.extend(file_unknowns) findings = hits_to_findings(hits) return findings, unknowns def _overlaps_change(hit: ScanHit, added: list[int]) -> bool: if not added: return True span = set(range(hit.start_line, hit.end_line + 1)) return bool(span & set(added))