---
title: Avoid Eval Or Dynamic Code Execution
impact: CRITICAL
impactDescription: prevents Remote Code Execution (RCE) vulnerabilities
tags: eval, code-execution, rce, injection, security, kotlin
---

## Avoid Eval Or Dynamic Code Execution

Executing code dynamically based on user input (e.g., using Script Engines or Reflection) is extremely dangerous. It allows attackers to execute arbitrary commands on the host system, leading to full server compromise.

**Incorrect (dynamic code execution):**

```kotlin
// Using JavaScript engine with user input
val engine = ScriptEngineManager().getEngineByName("javascript")
val userInput = request.getParameter("formula")
val result = engine.eval(userInput) // RCE vulnerability!

// Reflection with user-provided class names
val className = request.getParameter("type")
val instance = Class.forName(className).getDeclaredConstructor().newInstance()
// Attacker can pass "java.lang.ProcessBuilder"
```

**Correct (safe alternatives):**

```kotlin
// Use a specialized safe expression parser (e.g., exp4j)
val expression = ExpressionBuilder(userInput)
    .variables("x")
    .build()
val result = expression.setVariable("x", 10.0).evaluate()

// Use a predefined map for dynamic behavior
val operations = mapOf<String, (Int, Int) -> Int>(
    "add" to { a, b -> a + b },
    "subtract" to { a, b -> a - b }
)
val operation = operations[userInput] ?: throw IllegalArgumentException("Invalid operation")
val result = operation(10, 5)

// For mapping types, use a factory with an allowlist
fun createService(type: String): Service = when(type) {
    "email" -> EmailService()
    "sms" -> SmsService()
    else -> throw IllegalArgumentException("Unsupported type")
}
```

**Never use with user input:**
- `ScriptEngine.eval()`
- `Runtime.getRuntime().exec()` without extreme sanitization (prefer `ProcessBuilder`)
- `Class.forName(userInput)`
- SpEL (Spring Expression Language) with untrusted input

**Tools:** SonarQube (S1523), Semgrep, detekt, Manual Security Audit
