T09 · Insecure Skill Coding Practices
- Location
scripts/calc.py:116- Finding
Arbitrary Code Execution Through Unsafe Mathematical Expression Evaluation
- Content
View full analysis
float: """Evaluate a math expression using numpy.""" import numpy as np safe_ns = { "sin": np.sin, "cos": np.cos, "tan": np.tan, "asin": np.arcsin, "acos": np.arccos, "atan": np.arctan, "sinh": np.sinh, "cosh": np.cosh, "tanh": np.tanh, "sqrt": np.sqrt, "cbrt": np.cbrt, "log": np.log, "log2": np.log2, "log10": np.log10, "exp": np.exp, "abs": np.abs, "floor": np.floor, "ceil": np.ceil, "round": np.round, "pi": np.pi, "e": np.e, "inf": np.inf, "nan": np.nan, "np": np, } try: result = eval(expr, {"__builtins__": {}}, safe_ns) return float(result) ``` Additional user-controlled expression evaluation occurs in the mpmath, optimization, integration, and ODE paths at `scripts/calc.py:150-182`, `scripts/calc.py:482-496`, `scripts/calc.py:542-556`, and `scripts/calc.py:570-590`. ### Technical Analysis Removing `__builtins__` from the globals dictionary does not turn Python `eval()` into a secure expression parser. Python expressions still support attribute access, dictionary subscripting, calls, and traversal through objects supplied in the local namespace. The NumPy evaluator directly exposes the NumPy module as `np`. Python modules normally retain a reference to their builtins dictionary through `__builtins__`. A malicious expression can therefore traverse from `np` to the import function, import a system module, and invoke operating-system functionality. Conceptually, the escape follows this chain: ```text np -> np.__builtins__ -> ["__import__"] -> import an operating-system module -> invo ...[truncated 1938 chars]- Remediation
View remediation
