-
-
Notifications
You must be signed in to change notification settings - Fork 10
fix(math): restrict sympy expression parsing #200
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Rahul Dass (rahuldass19)
merged 8 commits into
QWED-AI:main
from
sebastiondev:fix/cwe95-main-sympy-9383
Jun 14, 2026
Merged
Changes from 1 commit
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
dc9d4db
fix: restrict sympy parse_expr to prevent code execution (CWE-95)
sebastiondev bbf9ade
fix: address review — add Greek symbols, copy global_dict per call, v…
sebastiondev e1454de
fix: resolve Sentry symbol mismatch and address CodeRabbit feedback
rahuldass19 356577d
fix: resolve CodeQL, Sentry, and CodeRabbit review feedback
rahuldass19 d72bc45
fix: post-parse sympy depth check, revert implicit-mult regression
rahuldass19 430686b
fix: treat lowercase e as variable, not Euler constant
rahuldass19 2b0f24d
fix: preserve error messages, reject relational expressions
rahuldass19 70f0978
fix: validate extra_symbols keys against denylist
rahuldass19 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,199 @@ | ||
| """ | ||
| Safe wrapper around sympy's parse_expr to prevent code execution. | ||
|
|
||
| sympy.parsing.sympy_parser.parse_expr() uses Python eval() internally. | ||
| Without restrictions on local_dict/global_dict, an attacker can execute | ||
| arbitrary code via crafted math expressions (CWE-95). | ||
|
|
||
| This module provides safe_parse_expr() which: | ||
| 1. Validates input against a denylist of dangerous patterns | ||
| 2. Restricts the eval namespace to only known-safe sympy objects | ||
| 3. Strips Python builtins from the global namespace | ||
|
|
||
| Usage: | ||
| from qwed_new.core.safe_parser import safe_parse_expr | ||
| expr = safe_parse_expr("x**2 + 2*x + 1") | ||
| """ | ||
|
|
||
| import re | ||
| import logging | ||
| from typing import Optional, Dict, Any | ||
|
|
||
| import sympy | ||
| from sympy import ( | ||
| Symbol, Integer, Float, Rational, | ||
| pi, E, oo, I, | ||
| ) | ||
| from sympy.parsing.sympy_parser import ( | ||
| parse_expr, | ||
| standard_transformations, | ||
| implicit_multiplication_application, | ||
| ) | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
| # Transformations that enable natural math input (e.g. "2x" → "2*x") | ||
| SAFE_TRANSFORMATIONS = standard_transformations + (implicit_multiplication_application,) | ||
|
|
||
| # Patterns that must never appear in math expressions. | ||
| # Checked before the string reaches parse_expr / eval. | ||
| _DANGEROUS_PATTERNS = re.compile( | ||
|
Check warning on line 40 in src/qwed_new/core/safe_parser.py
|
||
| r"__\w+__|" # dunder attributes (__import__, __class__, …) | ||
| r"\bimport\b|" # import keyword | ||
| r"\bexec\b|" # exec() | ||
| r"\beval\b|" # eval() | ||
| r"\bgetattr\b|" # getattr() | ||
| r"\bsetattr\b|" # setattr() | ||
| r"\bdelattr\b|" # delattr() | ||
| r"\bglobals\b|" # globals() | ||
| r"\blocals\b|" # locals() | ||
| r"\bcompile\b|" # compile() | ||
| r"\bopen\b|" # open() | ||
| r"\bbreakpoint\b|" # breakpoint() | ||
| r"\bprint\b|" # print() | ||
| r"\binput\b|" # input() | ||
| r"\bvars\b|" # vars() | ||
| r"\bdir\b|" # dir() | ||
| r"\btype\b|" # type() | ||
| r"\bsuper\b|" # super() | ||
| r"\bsubclasses\b|" # __subclasses__() | ||
| r"\bmro\b|" # mro() | ||
| r"\bbases\b|" # __bases__ | ||
| r"\bos\b|" # os module | ||
| r"\bsys\b|" # sys module | ||
| r"\bsubprocess\b", # subprocess module | ||
| re.IGNORECASE, | ||
| ) | ||
|
|
||
|
|
||
| def _build_safe_local_dict(extra_symbols: Optional[Dict[str, Any]] = None) -> dict: | ||
| """ | ||
| Build the allow-listed local namespace for parse_expr. | ||
|
|
||
| Only mathematical symbols, constants, functions, and the internal | ||
| sympy types that parse_expr's transformations emit are included. | ||
| """ | ||
| safe = { | ||
| # Common symbolic variables | ||
| "x": Symbol("x"), | ||
| "y": Symbol("y"), | ||
| "z": Symbol("z"), | ||
| "a": Symbol("a"), | ||
| "b": Symbol("b"), | ||
| "c": Symbol("c"), | ||
| "n": Symbol("n", integer=True, positive=True), | ||
| "t": Symbol("t"), | ||
| "r": Symbol("r"), | ||
| "k": Symbol("k"), | ||
| "m": Symbol("m"), | ||
| "p": Symbol("p"), | ||
| "q": Symbol("q"), | ||
| "u": Symbol("u"), | ||
| "v": Symbol("v"), | ||
| "w": Symbol("w"), | ||
| # Mathematical constants | ||
| "pi": pi, | ||
| "e": E, | ||
| "E": E, | ||
| "I": I, | ||
| "oo": oo, | ||
| # Trigonometric functions | ||
| "sin": sympy.sin, | ||
| "cos": sympy.cos, | ||
| "tan": sympy.tan, | ||
| "cot": sympy.cot, | ||
| "sec": sympy.sec, | ||
| "csc": sympy.csc, | ||
| # Inverse trigonometric | ||
| "asin": sympy.asin, | ||
| "acos": sympy.acos, | ||
| "atan": sympy.atan, | ||
| "atan2": sympy.atan2, | ||
| # Hyperbolic | ||
| "sinh": sympy.sinh, | ||
| "cosh": sympy.cosh, | ||
| "tanh": sympy.tanh, | ||
| # Logarithmic / exponential | ||
| "log": sympy.log, | ||
| "ln": sympy.log, | ||
| "exp": sympy.exp, | ||
| # Roots and absolute value | ||
| "sqrt": sympy.sqrt, | ||
| "cbrt": sympy.cbrt, | ||
| "abs": sympy.Abs, | ||
| "Abs": sympy.Abs, | ||
| # Combinatorial | ||
| "factorial": sympy.factorial, | ||
| "binomial": sympy.binomial, | ||
| # Sympy internal types emitted by standard_transformations | ||
| "Integer": Integer, | ||
| "Float": Float, | ||
| "Rational": Rational, | ||
| "Symbol": Symbol, | ||
| } | ||
|
|
||
| if extra_symbols: | ||
| # Only allow Symbol instances or sympy types as overrides | ||
| for key, value in extra_symbols.items(): | ||
| if isinstance(value, (Symbol, sympy.Basic)): | ||
| safe[key] = value | ||
|
|
||
| return safe | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
|
|
||
|
|
||
| # Pre-built global dict that strips builtins | ||
| _SAFE_GLOBAL_DICT: dict = {"__builtins__": {}} | ||
|
|
||
|
|
||
| def safe_parse_expr( | ||
| expression: str, | ||
| *, | ||
| transformations=SAFE_TRANSFORMATIONS, | ||
| extra_symbols: Optional[Dict[str, Any]] = None, | ||
| ) -> sympy.Basic: | ||
| """ | ||
| Safely parse a mathematical expression string into a sympy expression. | ||
|
|
||
| Raises ValueError if the expression contains dangerous patterns or | ||
| cannot be parsed. | ||
|
|
||
| Args: | ||
| expression: The math expression string to parse. | ||
| transformations: sympy transformations to apply (default includes | ||
| implicit multiplication). | ||
| extra_symbols: Additional Symbol mappings to include in the | ||
| local namespace. | ||
|
|
||
| Returns: | ||
| A sympy expression object. | ||
|
|
||
| Raises: | ||
| ValueError: If the expression is rejected by safety checks or | ||
| cannot be parsed. | ||
| """ | ||
| if not isinstance(expression, str): | ||
| raise ValueError("Expression must be a string") | ||
|
|
||
| stripped = expression.strip() | ||
| if not stripped: | ||
| raise ValueError("Expression must not be empty") | ||
|
|
||
| # Length limit to prevent resource exhaustion | ||
| if len(stripped) > 5000: | ||
| raise ValueError("Expression too long (max 5000 characters)") | ||
|
|
||
| # Deny-list check: reject expressions with dangerous patterns | ||
| if _DANGEROUS_PATTERNS.search(stripped): | ||
| raise ValueError("Expression contains disallowed constructs") | ||
|
|
||
| local_dict = _build_safe_local_dict(extra_symbols) | ||
|
|
||
| try: | ||
| return parse_expr( | ||
| stripped, | ||
| local_dict=local_dict, | ||
| global_dict=_SAFE_GLOBAL_DICT, | ||
| transformations=transformations, | ||
| ) | ||
|
greptile-apps[bot] marked this conversation as resolved.
|
||
| except Exception as exc: | ||
| raise ValueError(f"Failed to parse expression: {exc}") from exc | ||
|
coderabbitai[bot] marked this conversation as resolved.
Outdated
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.