forked from QWED-AI/qwed-verification
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsafe_parser.py
More file actions
199 lines (173 loc) · 5.92 KB
/
Copy pathsafe_parser.py
File metadata and controls
199 lines (173 loc) · 5.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
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(
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
# 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,
)
except Exception as exc:
raise ValueError(f"Failed to parse expression: {exc}") from exc