Back
+20 XP
Concept

Building a Safe Math Evaluator with AST

Using `eval()` on user inputs invites remote code execution (RCE). Parsing arithmetic with `ast.parse(mode='eval')` and evaluating only whitelisted AST math nodes creates an airtight, sandboxed evaluation engine 🛡️.

python
import ast
import operator

OPS = {ast.Add: operator.add, ast.Mult: operator.mul}

def eval_math(node):
    if isinstance(node, ast.Expression):
        return eval_math(node.body)
    if isinstance(node, ast.Constant):
        return node.value
    if isinstance(node, ast.BinOp):
        return OPS[type(node.op)](eval_math(node.left), eval_math(node.right))
    raise ValueError(f"Disallowed node: {type(node).__name__}")

tree = ast.parse("2 + 3 * 4", mode="eval")
print(f"Result: {eval_math(tree)} 🛡️")

# 66. Building a Safe Math Evaluator with AST Using `eval()` on user inputs invites remote code execution (RCE). Parsing arithmetic with `ast.parse(mode='eval')` and evaluating only whitelisted AST math nodes creates an airtight, sandboxed evaluation engine 🛡️. ```python import ast import operator OPS = {ast.Add: operator.add, ast.Mult: operator.mul} def eval_math(node): if isinstance(node, ast.Expression): return eval_math(node.body) if isinstance(node, ast.Constant): return node.value if isinstance(node, ast.BinOp): return OPS[type(node.op)](eval_math(node.left), eval_math(node.right)) raise ValueError(f"Disallowed node: {type(node).__name__}") tree = ast.parse("2 + 3 * 4", mode="eval") print(f"Result: {eval_math(tree)} 🛡️") ``` By specifying `mode='eval'`, the parser enforces that the input string is a single expression rather than multi-line statements, preventing assignments or function definitions upfront 🛡️! --- ### Question Why is an AST-based evaluator immune to arbitrary code execution attacks like `__import__('os').system(...)`? 🧠 - [ ] a. It strictly processes whitelisted math nodes (`BinOp`, `Constant`) and rejects `Call` or `Import` nodes 🛡️ - [ ] b. It executes parsed expressions inside an isolated system kernel namespace - [ ] c. It hashes source strings to ensure no shell commands can be formatted - [ ] d. The Python interpreter disables file system access during all AST parsing calls --- ### Challenge Implement `eval_math(node)` supporting `ast.Add`, `ast.Mult`, and `ast.Constant`. Evaluate `ast.parse('2 + 3 * 4', mode='eval')` and print the result. 🎯 <details> <summary>Solution</summary> ```python import ast import operator OPS = {ast.Add: operator.add, ast.Mult: operator.mul} def eval_math(node): if isinstance(node, ast.Expression): return eval_math(node.body) if isinstance(node, ast.Constant): return node.value if isinstance(node, ast.BinOp): return OPS[type(node.op)](eval_math(node.left), eval_math(node.right)) raise ValueError("Unsupported") tree = ast.parse('2 + 3 * 4', mode='eval') print(eval_math(tree)) ``` </details>

Checkpoint

Why is an AST-based evaluator immune to arbitrary code execution attacks like `__import__('os').system(...)`? 🧠

Practice

Implement `eval_math(node)` supporting `ast.Add`, `ast.Mult`, and `ast.Constant`. Evaluate `ast.parse('2 + 3 * 4', mode='eval')` and print the result. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks