#!/usr/bin/env python3 """Локальная проверка исходников без записи. Только стандартная библиотека. Код проекта не импортируется и не запускается. Правила берутся только из этого репозитория; поиск правил внутри проверяемого проекта не выполняется. """ from __future__ import annotations import argparse import ast from bisect import bisect_right from collections import Counter from datetime import datetime, timezone import fnmatch import hashlib import json import os from pathlib import Path import re import stat import sys import tokenize import io import unicodedata VERSION = "1.8.0" SCOPE_SCHEMA = "wahrwelt.scanner-scope.v2" CONTEXT_SCHEMA = "wahrwelt.scanner-context.v1" SEMANTIC_REVISION = "bounded-source-signals.v3" INFRASTRUCTURE = {"docker-desktop", "compose", "vulnbox", "team-lan", "s4dfarm", "neo", "packmate"} PATH_SEMANTICS = "root-relative-posix.v1" RULE_PATH = Path(__file__).resolve().parents[1] / "rules" / "defense.json" SKIP_DIRS = {".git", ".hg", ".svn", ".venv", "venv", "node_modules", "vendor", "__pycache__", ".cache", ".ssh", ".aws", "artifacts", "dist", "build", "target", "obj", "bin"} EXTENSIONS = { ".py": "python", ".js": "javascript", ".jsx": "javascript", ".ts": "javascript", ".tsx": "javascript", ".mjs": "javascript", ".cjs": "javascript", ".php": "php", ".go": "go", ".java": "java", ".cs": "csharp", ".c": "native", ".h": "native", ".cpp": "native", ".hpp": "native", ".cc": "native", ".yaml": "config", ".yml": "config", ".toml": "config", ".json": "config", ".conf": "config", ".ini": "config", ".properties": "config", ".xml": "config", ".sh": "shell", ".bash": "shell", ".ejs": "template", ".html": "template", ".hbs": "template", ".j2": "template", ".twig": "template", ".erb": "template", ".rb": "ruby", ".rake": "ruby", ".rs": "rust", ".sql": "sql", ".acl": "config", ".cnf": "config", ".config": "config", ".cshtml": "csharp", ".razor": "csharp", ".service": "config", ".socket": "config", } def load_rules(): data = json.loads(RULE_PATH.read_text(encoding="utf-8")) if data["schema_version"] != 1: raise ValueError("unsupported rules schema") rules = data["rules"] if len({r["id"] for r in rules}) != len(rules): raise ValueError("duplicate rule IDs") for rule in rules: for field in ("id", "title", "engine", "languages", "reason", "fix", "before", "after", "check", "doc", "family", "limitations"): if not rule.get(field): raise ValueError("incomplete rule: " + rule.get("id", "?")) if (rule.get("review_priority") not in {"normal", "high"} or rule.get("signal_kind") not in {"syntactic-review", "configuration-review"} or not isinstance(rule.get("cwe"), list) or any(not isinstance(item, str) or not re.fullmatch(r"CWE-[1-9][0-9]*", item) for item in rule["cwe"]) or type(rule.get("code_only", False)) is not bool): raise ValueError("invalid rule metadata") if rule["engine"] == "regex": rule["compiled"] = re.compile(rule["pattern"], re.MULTILINE | re.IGNORECASE) rule["compiled_languages"] = {} variants = rule.get("language_patterns", {}) if not isinstance(variants, dict): raise ValueError("language patterns must be a mapping") for lang, pattern in variants.items(): if lang not in rule["languages"] or not isinstance(pattern, str): raise ValueError("invalid language pattern") rule["compiled_languages"][lang] = re.compile(pattern, re.MULTILINE | re.IGNORECASE) elif rule["engine"] not in {"python-ast", "javascript-tokens"}: raise ValueError("unknown engine") return rules def _canonical_json(value): return json.dumps(value, ensure_ascii=True, sort_keys=True, separators=(",", ":")).encode("utf-8") def validate_context(value=None): """Контекст содержит только разрешенные значения и не отключает правила.""" if value is None: value = {"schema": CONTEXT_SCHEMA, "infrastructure": [], "role": "both"} if not isinstance(value, dict) or set(value) != {"schema", "infrastructure", "role"}: raise ValueError("invalid scanner context") items = value["infrastructure"] if (value["schema"] != CONTEXT_SCHEMA or value["role"] not in ("defender", "administrator", "both") or not isinstance(items, list) or len(items) > len(INFRASTRUCTURE) or any(not isinstance(item, str) or item not in INFRASTRUCTURE for item in items) or len(items) != len(set(items))): raise ValueError("invalid scanner context") return {"schema": CONTEXT_SCHEMA, "infrastructure": sorted(items), "role": value["role"]} def _unique_json_object(pairs): result = {} for key, value in pairs: if key in result: raise ValueError("duplicate JSON key") result[key] = value return result def load_context(filename): return validate_context(json.loads(read_regular(canonical_scan_root(filename), 16384), object_pairs_hook=_unique_json_object)) def review_metadata(rule, context): """Пояснения берутся из правил, а не из проверяемых исходников.""" notes = [] active = set(context["infrastructure"]) family = rule["family"] if active & {"compose", "docker-desktop"} and family == "container-isolation": notes.append("Проверьте эту настройку в итоговой конфигурации; исходный текст не подтверждает поведение runtime.") if active & {"team-lan", "s4dfarm", "neo", "packmate"} and family in {"authentication", "secret-handling", "network-exposure"}: notes.append("Проверьте доступ с отдельного разрешенного клиента LAN; не выводите учетные данные в логи и трансляцию.") if "vulnbox" in active and family in {"injection", "file-access", "authentication"}: notes.append("До изменения сервиса проверьте его контракт и поведение проверяющей системы.") return {"family": family, "cwe": list(rule["cwe"]), "review_priority": "high" if notes else rule["review_priority"], "signal_kind": rule["signal_kind"], "limitations": rule["limitations"], "context_notes": notes} def rules_fingerprint(rules): """Хешируем данные правил без скомпилированных регулярных выражений.""" portable = [] for rule in sorted(rules, key=lambda item: item["id"]): portable.append({key: value for key, value in rule.items() if key not in {"compiled", "compiled_languages"}}) return hashlib.sha256(_canonical_json(portable)).hexdigest() def scan_scope(root, rules, exclude, max_bytes, max_files, max_findings, context=None): """Описание области проверки для сравнения отчетов, без секретов.""" normalized_root = unicodedata.normalize("NFC", os.path.normcase(str(root))) root_digest = hashlib.sha256( ("wahrwelt-root-v1\0" + normalized_root).encode( "utf-8", errors="surrogatepass" ) ).hexdigest() body = { "schema": SCOPE_SCHEMA, "root": "sha256:" + root_digest, "rules_sha256": rules_fingerprint(rules), "exclude": sorted(set(exclude)), "limits": { "max_bytes": max_bytes, "max_files": max_files, "max_findings": max_findings, }, "path_semantics": PATH_SEMANTICS, "semantic_revision": SEMANTIC_REVISION, "context_sha256": hashlib.sha256(_canonical_json(validate_context(context))).hexdigest(), } body["sha256"] = hashlib.sha256(_canonical_json(body)).hexdigest() return body def language(path): name = path.name.lower() if name.startswith("dockerfile"): return "docker" if name == ".env.example" or name in {"nginx.conf", "redis.conf", "my.cnf", ".htaccess", "sshd_config", "sudoers"}: return "config" if name in {"gemfile", "rakefile"}: return "ruby" return EXTENSIONS.get(path.suffix.lower()) class PythonSignals(ast.NodeVisitor): """Синтаксические признаки без вывода типов и анализа потоков данных.""" def __init__(self): self.aliases = {} # Учитываем только неизменяемые скалярные факты в линейном коде. # Не вычисляем код, изменяемые коллекции и связи между функциями. self.values = {} self.hits = set() self.issues = set() self.replaced_api_members = set() def resolved(self, node): return self.values.get(node.id, node) if isinstance(node, ast.Name) else node @staticmethod def literal_dict(node): """Ключи литерала словаря с учетом порядка распаковки. Неизвестные ключи отменяют предыдущие факты. Переменные не вычисляются. """ result = {} if not isinstance(node, ast.Dict): return result for key, value in PythonSignals.dict_entries(node): if key is None: result.clear() else: result[key] = value return result @staticmethod def dict_entries(node): for key, value in zip(node.keys, node.values): if key is None and isinstance(value, ast.Dict): yield from PythonSignals.dict_entries(value) elif isinstance(key, ast.Constant) and isinstance(key.value, str): yield key.value, value else: yield None, None INSTANCE_FACTORIES = {"requests.Session": "requests.Session", "requests.sessions.Session": "requests.Session", "requests.session": "requests.Session", "requests.sessions.session": "requests.Session", "httpx.Client": "httpx.Client", "httpx.AsyncClient": "httpx.AsyncClient", "pickle.Unpickler": "pickle.Unpickler", "_pickle.Unpickler": "_pickle.Unpickler", "flask.Flask": "flask.Flask", "flask.Blueprint": "flask.Blueprint", "logging.getLogger": "logging.Logger"} TAR_FACTORIES = {"tarfile.open": "tarfile.TarFile", "tarfile.TarFile": "tarfile.TarFile", "tarfile.TarFile.open": "tarfile.TarFile"} def constructed_type(self, node): if not isinstance(node, ast.Call): return "" factory = self.name(node.func) if factory in {"flask.Flask", "flask.Blueprint", "logging.getLogger"} and not self.known_binding(node.func): return "" return self.TAR_FACTORIES.get(factory, self.INSTANCE_FACTORIES.get(factory, "")) def known_binding(self, node): """Есть ли для имени явный локальный факт.""" if isinstance(node, ast.Name): return node.id in self.aliases and self.aliases[node.id] != "" if isinstance(node, ast.Attribute): return self.name(node) not in self.replaced_api_members and self.known_binding(node.value) if isinstance(node, ast.Call): return self.known_binding(node.func) return False def forget(self, target): for item in ast.walk(target): if isinstance(item, ast.Attribute) and isinstance(item.ctx, (ast.Store, ast.Del)): self.replaced_api_members.add(self.name(item)) if isinstance(item, ast.Name) and isinstance(item.ctx, (ast.Store, ast.Del)): self.values.pop(item.id, None) self.aliases[item.id] = "" def visit_Assign(self, node): self.visit(node.value) value = self.resolved(node.value) factory = self.constructed_type(node.value) for target in node.targets: self.visit(target) self.forget(target) if isinstance(target, ast.Name) and (isinstance(value, ast.Constant) or self.dynamic_string(value) or self.psycopg_sql(value) != "unknown"): self.values[target.id] = value elif isinstance(target, ast.Name) and factory: self.aliases[target.id] = factory for target in node.targets: if isinstance(target, ast.Attribute): self.replaced_api_members.add(self.name(target)) if (isinstance(target, ast.Subscript) and self.flask_config(target.value) and isinstance(target.slice, ast.Constant)): self.config_signal(target.slice.value, node.value, node) if isinstance(target, ast.Attribute): if (target.attr == "debug" and self.name(target.value) == "flask.Flask" and self.known_binding(target.value) and self.constant(node.value, True)): self.hit("PY-DEBUG", node) if target.attr == "verify_mode" and self.name(node.value) == "ssl.CERT_NONE": self.hit("PY-SSL-CONTEXT", node) if target.attr == "check_hostname" and self.constant(node.value, False): self.hit("PY-SSL-CONTEXT", node) def visit_AnnAssign(self, node): if node.value is not None: # Повторно используем обработку присваивания, сохраняя номер строки. assignment = ast.Assign(targets=[node.target], value=node.value) ast.copy_location(assignment, node) self.visit_Assign(assignment) else: self.forget(node.target) def visit_AugAssign(self, node): self.generic_visit(node) self.forget(node.target) def visit_NamedExpr(self, node): self.visit(node.value) self.forget(node.target) def visit_Delete(self, node): for target in node.targets: self.forget(target) def visit_branch(self, node): # Факты не переходят через ветвления, циклы, обработчики исключений, # генераторы и менеджеры контекста. Каждый блок проверяется отдельно. self.values = {} saved = self.aliases.copy() for _, value in ast.iter_fields(node): if isinstance(value, list): self.values = {} self.aliases = saved.copy() for child in value: if isinstance(child, ast.AST): self.visit(child) elif isinstance(value, ast.AST): self.visit(value) self.invalidate_region_aliases(node, saved) self.values = {} def invalidate_region_aliases(self, node, saved): # Присваивание или импорт внутри условия делает псевдоним неоднозначным. self.aliases = saved for child in ast.walk(node): if isinstance(child, ast.Name) and isinstance(child.ctx, (ast.Store, ast.Del)): self.aliases[child.id] = "" elif isinstance(child, (ast.Import, ast.ImportFrom)): for alias in child.names: self.aliases[alias.asname or alias.name.split(".")[0]] = "" def visit_context(self, node, *, asynchronous): # Сохраняем лишь известные конструкторы с подходящим API контекста. # __enter__/__exit__ могут менять состояние; сканер их не исполняет. allowed = {"httpx.AsyncClient"} if asynchronous else {"tarfile.TarFile", "requests.Session", "httpx.Client"} saved = self.aliases.copy() self.values = {} for item in node.items: self.visit(item.context_expr) context_type = self.name(item.context_expr) if item.optional_vars is not None: self.forget(item.optional_vars) if isinstance(item.optional_vars, ast.Name) and context_type in allowed: self.aliases[item.optional_vars.id] = context_type for statement in node.body: self.visit(statement) self.invalidate_region_aliases(node, saved) self.values = {} def visit_With(self, node): self.visit_context(node, asynchronous=False) def visit_AsyncWith(self, node): self.visit_context(node, asynchronous=True) visit_If = visit_branch visit_For = visit_branch visit_AsyncFor = visit_branch visit_While = visit_branch visit_Try = visit_branch visit_TryStar = visit_branch visit_Match = visit_branch visit_IfExp = visit_branch visit_ListComp = visit_branch visit_SetComp = visit_branch visit_DictComp = visit_branch visit_GeneratorExp = visit_branch def name(self, node): if isinstance(node, ast.Name): return self.aliases.get(node.id, node.id) if isinstance(node, ast.Attribute): return self.name(node.value) + "." + node.attr if isinstance(node, ast.Call): return self.constructed_type(node) return "" def visit_Import(self, node): for alias in node.names: self.values.pop(alias.asname or alias.name.split(".")[0], None) self.aliases[alias.asname or alias.name.split(".")[0]] = alias.name if alias.asname else alias.name.split(".")[0] def visit_ImportFrom(self, node): if node.module: for alias in node.names: if alias.name != "*": self.values.pop(alias.asname or alias.name, None) self.aliases[alias.asname or alias.name] = node.module + "." + alias.name def visit_FunctionDef(self, node): saved, saved_values = self.aliases.copy(), self.values.copy() auth_seen = False for decorator in node.decorator_list: # Внешние декораторы идут первыми. Декоратор маршрута Flask # должен оборачивать декоратор аутентификации. if self.name(decorator) == "flask_login.login_required" and self.known_binding(decorator): auth_seen = True if (auth_seen and isinstance(decorator, ast.Call) and self.name(decorator.func) in { "flask.Flask.route", "flask.Blueprint.route", *{"flask." + kind + "." + method for kind in ("Flask", "Blueprint") for method in ("get", "post", "put", "patch", "delete")}}): self.hit("PY-AUTH-DECORATOR", decorator) if self.name(decorator) == "django.views.decorators.csrf.csrf_exempt": self.hit("PY-CSRF-EXEMPT", decorator) self.visit(decorator) for default in [*node.args.defaults, *node.args.kw_defaults]: if default is not None: self.visit(default) self.values = {} # Параметры скрывают импорты. Факты функции не выходят за ее границы. arguments = node.args.posonlyargs + node.args.args + node.args.kwonlyargs arguments += [arg for arg in (node.args.vararg, node.args.kwarg) if arg] for arg in arguments: self.aliases[arg.arg] = "" for statement in node.body: self.visit(statement) self.aliases = saved self.aliases[node.name] = "" self.values = saved_values self.values.pop(node.name, None) visit_AsyncFunctionDef = visit_FunctionDef def visit_ClassDef(self, node): saved, saved_values = self.aliases.copy(), self.values.copy() self.values = {} self.generic_visit(node) self.aliases = saved self.aliases[node.name] = "" self.values = saved_values self.values.pop(node.name, None) def visit_Lambda(self, node): saved, saved_values = self.aliases.copy(), self.values.copy() for default in [*node.args.defaults, *node.args.kw_defaults]: if default is not None: self.visit(default) for arg in [*node.args.posonlyargs, *node.args.args, *node.args.kwonlyargs, *[a for a in (node.args.vararg, node.args.kwarg) if a]]: self.aliases[arg.arg] = "" self.values = {} self.visit(node.body) self.aliases, self.values = saved, saved_values def constant(self, node, value): node = self.resolved(node) return isinstance(node, ast.Constant) and node.value == value @staticmethod def literal_string(node): # Проверяем синтаксис без вычислений и рекурсивного раскрытия имен. if isinstance(node, ast.Constant): return isinstance(node.value, str) if isinstance(node, ast.JoinedStr): return all(isinstance(part, ast.Constant) and isinstance(part.value, str) for part in node.values) return (isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add) and PythonSignals.literal_string(node.left) and PythonSignals.literal_string(node.right)) def dynamic_string(self, node): node = self.resolved(node) if self.literal_string(node): return False return (isinstance(node, ast.JoinedStr) or isinstance(node, ast.BinOp) and isinstance(node.op, (ast.Add, ast.Mod)) or isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) and node.func.attr == "format") def flask_config(self, node): return (isinstance(node, ast.Attribute) and node.attr == "config" and self.name(node.value) == "flask.Flask" and self.known_binding(node)) def config_signal(self, key, value, node): if key == "DEBUG" and self.constant(value, True): self.hit("PY-DEBUG", node) if key in {"SESSION_COOKIE_HTTPONLY", "SESSION_COOKIE_SECURE"} and self.constant(value, False): self.hit("CFG-COOKIE-FLAGS", node) def psycopg_sql(self, node, depth=0, active=None): """Оцениваем дерево SQL-композиции: safe, unsafe или unknown. SQL() не экранирует аргумент. Исключаем только литералы и известные конструкторы экранирования. Права на выбор идентификатора не проверяются. """ node = self.resolved(node) active = set() if active is None else active if id(node) in active: return "unknown" # A scalar/name cycle is not deep composition. if depth > 32: self.issues.add("python_composition_limit") return "unknown" active = active | {id(node)} if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add): states = [self.psycopg_sql(part, depth + 1, active) for part in (node.left, node.right)] return "unsafe" if "unsafe" in states else "safe" if states == ["safe", "safe"] else "unknown" if not isinstance(node, ast.Call): return "unknown" name = self.name(node.func) prefixes = ("psycopg.sql.", "psycopg2.sql.") if name.startswith(prefixes) and self.known_binding(node.func): kind = name.rsplit(".", 1)[-1] if kind == "SQL": return "safe" if len(node.args) == 1 and not node.keywords and self.literal_string(self.resolved(node.args[0])) else "unsafe" if kind in {"Identifier", "Literal", "Placeholder"}: return "safe" if isinstance(node.func, ast.Attribute) and node.func.attr in {"format", "join", "as_string"}: base = self.psycopg_sql(node.func.value, depth + 1, active) if base == "unknown": return "unknown" if node.func.attr == "as_string": return base if node.func.attr == "join": parts = node.args[0].elts if len(node.args) == 1 and isinstance(node.args[0], (ast.List, ast.Tuple)) else [None] else: parts = [*node.args, *[kw.value if kw.arg else None for kw in node.keywords]] states = [base, *[self.psycopg_sql(part, depth + 1, active) for part in parts]] return "safe" if all(state == "safe" for state in states) else "unsafe" return "unknown" def hit(self, rule, node): self.hits.add((rule, node.lineno)) def visit_Assert(self, node): # Защитные проверки должны работать с python -O. # Обычные тестовые assert исключены этой эвристикой по имени. sensitive = re.compile(r"(?:auth|permission|owner|admin|token|session|password|allowed)", re.I) if any(isinstance(item, ast.Name) and sensitive.search(item.id) or isinstance(item, ast.Attribute) and sensitive.search(item.attr) for item in ast.walk(node.test)): self.hit("PY-ASSERT-AUTH", node) self.generic_visit(node) def visit_Call(self, node): name = self.name(node.func) tail = name.rsplit(".", 1)[-1] kwargs = {} for kw in node.keywords: if kw.arg: kwargs[kw.arg] = kw.value else: kwargs.update(self.literal_dict(kw.value)) first = node.args[0] if node.args else None if (isinstance(node.func, ast.Attribute) and node.func.attr in {"update", "from_mapping"} and self.flask_config(node.func.value)): config = {} if len(node.args) <= 1: if node.args: config.update(self.literal_dict(node.args[0])) for kw in node.keywords: if kw.arg: config[kw.arg] = kw.value elif isinstance(kw.value, ast.Dict): for key, value in self.dict_entries(kw.value): if key is None: config.clear() else: config[key] = value else: config.clear() for key, value in config.items(): self.config_signal(key, value, node) if (self.known_binding(node.func) and name.rsplit(".", 1)[0] in {"logging", "logging.Logger", "flask.Flask.logger"} and tail in {"debug", "info", "warning", "warn", "error", "exception", "critical", "log"}): sensitive = {"password", "passwd", "secret", "token", "access_token", "refresh_token", "api_key", "authorization"} # Только прямые значения, без аргументов функций очистки или хеша. # Исходный текст в отчет не попадает. def exposes(value): if isinstance(value, ast.Name): return value.id.lower() in sensitive if isinstance(value, ast.Attribute): return value.attr.lower() in sensitive if isinstance(value, ast.Subscript): return isinstance(value.slice, ast.Constant) and isinstance(value.slice.value, str) and value.slice.value.lower() in sensitive if isinstance(value, ast.JoinedStr): return any(exposes(item.value) for item in value.values if isinstance(item, ast.FormattedValue)) if isinstance(value, (ast.Tuple, ast.List)): return any(exposes(item) for item in value.elts) if isinstance(value, ast.Dict): return any(exposes(item) for item in value.values) if isinstance(value, ast.BinOp): return exposes(value.left) or exposes(value.right) return False if any(exposes(value) for value in node.args): self.hit("PY-LOG-CREDENTIALS", node) if name in {"eval", "exec", "builtins.eval", "builtins.exec"}: self.hit("PY-EVAL", node) subprocess_call = name in {"subprocess.run", "subprocess.call", "subprocess.check_call", "subprocess.check_output", "subprocess.Popen"} process_args = first if first is not None else kwargs.get("args") if name == "asyncio.create_subprocess_exec": process_args = ast.Tuple(elts=node.args, ctx=ast.Load()) shell_argv = (isinstance(process_args, (ast.List, ast.Tuple)) and len(process_args.elts) > 1 and isinstance(process_args.elts[0], ast.Constant) and isinstance(process_args.elts[0].value, str) and process_args.elts[0].value.replace("\\", "/").rsplit("/", 1)[-1].lower() in {"sh", "bash", "dash", "zsh", "ksh", "cmd", "cmd.exe", "powershell", "powershell.exe", "pwsh"} and any(isinstance(arg, ast.Constant) and isinstance(arg.value, str) and arg.value.lower() in {"-c", "-lc", "-ec", "/c", "-command", "-encodedcommand"} for arg in process_args.elts[1:])) if (name in {"os.system", "os.popen", "subprocess.getoutput", "subprocess.getstatusoutput", "asyncio.create_subprocess_shell"} or subprocess_call and (self.constant(kwargs.get("shell"), True) or shell_argv) or name == "asyncio.create_subprocess_exec" and shell_argv): self.hit("PY-SHELL", node) if name in {"pickle.load", "pickle.loads", "_pickle.load", "_pickle.loads", "dill.load", "dill.loads", "shelve.open", "pickle.Unpickler.load", "_pickle.Unpickler.load", "jsonpickle.decode", "jsonpickle.loads", "joblib.load", "pandas.read_pickle"}: self.hit("PY-DESERIALIZE", node) if name in {"numpy.load", "numpy.lib.format.read_array"}: # Эти API запрещают pickle по умолчанию; ищем явное разрешение. # Распаковка аргументов мешает определить позиционный индекс. position = 2 if name == "numpy.load" else 1 allow_pickle = kwargs.get("allow_pickle") if (allow_pickle is None and len(node.args) > position and not any(isinstance(arg, ast.Starred) for arg in node.args[:position + 1])): allow_pickle = node.args[position] if self.constant(allow_pickle, True): self.hit("PY-DESERIALIZE", node) if name in {"yaml.load", "yaml.load_all", "yaml.unsafe_load", "yaml.unsafe_load_all"}: loader = kwargs.get("Loader", node.args[1] if len(node.args) > 1 else None) if self.name(loader) not in {"yaml.SafeLoader", "yaml.CSafeLoader", "yaml.BaseLoader", "yaml.CBaseLoader"}: self.hit("PY-YAML", node) sql_arg = first if sql_arg is None: sql_arg = next((kwargs[k] for k in ("query", "sql", "operation", "statement", "sql_script", "raw_query", "text") if k in kwargs), None) if tail in {"execute", "executemany", "executescript", "raw", "text"}: composition = self.psycopg_sql(sql_arg) if composition == "unsafe" or composition != "safe" and self.dynamic_string(sql_arg): self.hit("PY-SQL", node) if tail in {"find", "find_one", "filter", "where"} and any(isinstance(arg, ast.BoolOp) for arg in node.args): self.hit("PY-ORM-BOOL", node) template_arg = first if first is not None else kwargs.get("source") if tail in {"render_template_string", "from_string"} and template_arg is not None and not isinstance(template_arg, ast.Constant): self.hit("PY-TEMPLATE", node) if self.constant(kwargs.get("verify"), False) and (name.startswith(("requests.", "httpx.")) or tail in {"get", "post", "put", "patch", "delete", "request"}): self.hit("PY-TLS", node) if name == "ssl._create_unverified_context": self.hit("PY-SSL-CONTEXT", node) if name == "django.views.decorators.csrf.csrf_exempt": self.hit("PY-CSRF-EXEMPT", node) if name in {"setattr", "builtins.setattr"} and len(node.args) > 1 and not isinstance(self.resolved(node.args[1]), ast.Constant): self.hit("PY-MASS-ASSIGN", node) redirect_keyword = "to" if name == "django.shortcuts.redirect" else "location" redirect_arg = first if first is not None else kwargs.get(redirect_keyword) if name in {"flask.redirect", "django.shortcuts.redirect", "werkzeug.utils.redirect"} and redirect_arg is not None and not isinstance(self.resolved(redirect_arg), ast.Constant): self.hit("PY-REDIRECT", node) if name in {"re.compile", "re.match", "re.fullmatch", "re.search", "re.findall", "re.finditer", "re.split", "re.sub", "re.subn"} and first is not None and not isinstance(self.resolved(first), ast.Constant): self.hit("PY-REGEX-DYNAMIC", node) if tail in {"run", "run_simple"} and self.constant(kwargs.get("debug", kwargs.get("use_debugger")), True): self.hit("PY-DEBUG", node) if name in {"jwt.decode", "jwt.decode_complete"} or name.endswith((".jwt.decode", ".jwt.decode_complete")): jose = name == "jose.jwt.decode" known_modern = jose or name == "jwt.decode_complete" jwt_args = kwargs.copy() valid_binding = True if known_modern: # В PyJWT 1.x verify был третьим аргументом. # Такое расположение известно только для этих точных API. for argument, position in (("algorithms", 2), ("options", 3)): if (len(node.args) > position and not any(isinstance(arg, ast.Starred) for arg in node.args[:position + 1])): if argument in jwt_args: valid_binding = False # Runtime TypeError, not a disabled verifier. else: jwt_args[argument] = node.args[position] if valid_binding: options = self.literal_dict(jwt_args.get("options")) disabled = not known_modern and self.constant(jwt_args.get("verify"), False) disabled |= self.constant(options.get("verify_signature"), False) if any(self.constant(options.get("verify_" + claim), False) and not (jose and self.constant(options.get("require_" + claim), True)) for claim in ("exp", "nbf", "aud", "iss")): self.hit("PY-JWT-CLAIMS", node) if disabled: self.hit("PY-JWT", node) algorithms = jwt_args.get("algorithms") algorithm_value = self.resolved(algorithms) fixed_algorithms = (isinstance(algorithms, (ast.List, ast.Tuple)) and all(isinstance(a, ast.Constant) and isinstance(a.value, str) for a in algorithms.elts)) fixed_algorithms |= (jose and isinstance(algorithm_value, ast.Constant) and isinstance(algorithm_value.value, str)) if algorithms is not None and not fixed_algorithms: self.hit("PY-JWT-ALGORITHMS", node) archive_filter = kwargs.get("filter") data_filter = (self.constant(archive_filter, "data") or self.name(archive_filter) == "tarfile.data_filter") tar_extract = name == "tarfile.TarFile.extract" unpack_tar = False if name == "shutil.unpack_archive": archive_format = kwargs.get("format") if (archive_format is None and len(node.args) > 2 and not any(isinstance(arg, ast.Starred) for arg in node.args[:3])): archive_format = node.args[2] unpack_tar = any(self.constant(archive_format, fmt) for fmt in ("tar", "gztar", "bztar", "xztar", "zstdtar")) if (tail == "extractall" or tar_extract or unpack_tar) and not data_filter: self.hit("PY-ARCHIVE", node) if name in {"tempfile.mktemp"}: self.hit("PY-TEMP", node) if (tail == "XMLParser" or name in {"lxml.etree.XMLPullParser", "lxml.etree.ETCompatXMLParser", "lxml.etree.iterparse"}) and self.constant(kwargs.get("resolve_entities"), True): self.hit("PY-XML", node) if name in {"hashlib.md5", "hashlib.sha1"}: self.hit("PY-WEAK-HASH", node) if name.startswith("random.") and tail in {"random", "randint", "randrange", "getrandbits", "choice", "choices"}: self.hit("PY-RNG", node) file_arg = first if first is not None else kwargs.get("path_or_file") if tail == "send_file" and file_arg is not None and not isinstance(file_arg, ast.Constant): self.hit("PY-FILE", node) url_arg = first if first is not None else kwargs.get("url") http_owner = name.rsplit(".", 1)[0] http_call = (http_owner in {"requests", "httpx", "requests.Session", "requests.sessions.Session", "httpx.Client", "httpx.AsyncClient"} and tail in {"get", "post", "put", "patch", "delete", "head", "options", "request"}) http_call |= http_owner in {"httpx", "httpx.Client", "httpx.AsyncClient"} and tail == "stream" if http_call and tail in {"request", "stream"}: url_arg = (node.args[1] if len(node.args) > 1 and not any(isinstance(arg, ast.Starred) for arg in node.args[:2]) else kwargs.get("url")) if (http_call or name == "urllib.request.urlopen") and url_arg is not None and not isinstance(self.resolved(url_arg), ast.Constant): self.hit("PY-URL", node) if name in {"zlib.crc32", "zlib.adler32", "binascii.crc32", "binascii.crc_hqx"}: self.hit("PY-CRC", node) if tail in {"xpath", "XPath"} and self.dynamic_string(first): self.hit("PY-XPATH", node) if name == "uuid.UUID" and ({"bytes", "bytes_le"} & kwargs.keys()): self.hit("PY-UUID-BYTES", node) self.generic_visit(node) def javascript_alias_patterns(source): """Подсказки по импортам без полного разбора JavaScript и областей видимости. Учитываются лишь известные пары модуль-член; имена экранируются. """ ident = r"[A-Za-z_$][\w$]{0,127}" module = r"['\"]((?:node:)?child_process|jsonwebtoken|jose)['\"]" bindings = [] def bind(mod, local, member, end): mod = mod.removeprefix("node:") if not re.fullmatch(ident, local): return members = {"child_process": ("exec", "execSync", "spawn", "spawnSync", "execFile", "execFileSync"), "jsonwebtoken": ("decode",), "jose": ("decodeJwt",)}[mod] for name in members if member is None else (member,): if name not in members: continue if len(bindings) >= 128: raise ValueError("javascript_alias_limit") rid = "JS-SHELL" if mod == "child_process" else "JS-JWT-DECODE" receiver = re.escape(local) if member is None: access = r"\s*(?:\?\.\s*|\.\s*)" + re.escape(name) access += r"|\s*(?:\?\.\s*)?\[\s*['\"]" + re.escape(name) + r"['\"]\s*\]" receiver += "(?:" + access + ")" suffix = r"\s*(?:\?\.)?\s*\(" if mod == "child_process" and name not in {"exec", "execSync"}: suffix += r"\s*['\"](?:[^'\"\n]*/)?(?:sh|bash|dash|zsh|cmd(?:\.exe)?|powershell(?:\.exe)?|pwsh)['\"]" bindings.append((rid, re.compile(r"(?|\.\.\.|\?\.|===|==|!=|\+=|-=|\+\+|--|[^\s]") i = 0 while i < len(source): if source[i].isspace(): i += 1 continue if source.startswith("//", i): end = source.find("\n", i + 2) i = len(source) if end < 0 else end continue if source.startswith("/*", i): end = source.find("*/", i + 2) if end < 0: issues.append("lexical_unterminated") i = len(source) if end < 0 else end + 2 continue start = i if (source[i] == "/" and (not tokens or tokens[-1][0] in {"=", "(", "[", ":", ",", "return", "=>", "!", "?", ";"})): # Учитываем обычные позиции regex-литералов. # Неоднозначность с оператором деления требует ручной проверки. end, character_class = i + 1, False while end < len(source) and source[end] not in "\r\n": if source[end] == "\\": end += 2 continue if source[end] == "[": character_class = True elif source[end] == "]": character_class = False elif source[end] == "/" and not character_class: break end += 1 if end < len(source) and source[end] == "/": i = end + 1 tokens.append(("", start)) continue if source[i] in "\"'`": quote, closed = source[i], False i += 1 while i < len(source): if source[i] == "\\": i = min(len(source), i + 2) elif source[i] == quote: i += 1 closed = True break else: i += 1 if not closed: issues.append("lexical_unterminated") tokens.append(("