---
title: Avoid eval() or Dynamic Code Execution
impact: CRITICAL
impactDescription: prevents arbitrary code execution vulnerabilities
tags: injection, eval, dynamic-code, security, python, pyspark
---

## Avoid eval() or Dynamic Code Execution

Functions that execute strings as code (like `eval()` and `exec()`) are extremely dangerous. If an attacker can control part of the string, they can execute arbitrary commands on the server.

**Incorrect (dynamic code execution):**

```python
# Unsafe use of eval()
formula = request.args.get('formula')
result = eval(formula) # Attack: __import__('os').system('rm -rf /')

# Unsafe use of exec()
code_snippet = request.args.get('code')
exec(code_snippet)
```

**Correct (safe alternatives):**

```python
# Use a safe library for mathematical expressions
from simpleeval import simple_eval
formula = request.args.get('formula')
result = simple_eval(formula)

# Use explicit logic instead of dynamic code
def get_calculation(op, a, b):
    ops = {
        'add': lambda x, y: x + y,
        'sub': lambda x, y: x - y
    }
    return ops.get(op)(a, b)

# For PySpark: Avoid using custom Python functions (UDFs) with dynamic code
# Use built-in Spark SQL functions instead
from pyspark.sql import functions as F
df = df.withColumn("total", F.col("price") * F.col("quantity"))
```

**Benefits:**
- Eliminates Remote Code Execution (RCE) risks
- Improves performance (compiled code vs interpreted strings)
- Easier to debug and audit

**Tools:** Bandit (B307, B102), SonarQube, Semgrep
